]> git.ipfire.org Git - thirdparty/squid.git/blame - lib/GNUregex.c
Updates for running on squid-cache.org
[thirdparty/squid.git] / lib / GNUregex.c
CommitLineData
836c3244 1/*
cc192b50 2 * $Id: GNUregex.c,v 1.22 2007/12/14 23:11:44 amosjeffries Exp $
836c3244 3 */
4
090089c4 5/* Extended regular expression matching and search library,
b8d8561b 6 * version 0.12.
7 * (Implements POSIX draft P10003.2/D11.2, except for
8 * internationalization features.)
9 *
10 * Copyright (C) 1993 Free Software Foundation, Inc.
11 *
12 * This program is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation; either version 2, or (at your option)
15 * any later version.
16 *
17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
21 *
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, write to the Free Software
cbdec147 24 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. */
090089c4 25
26/* AIX requires this to be the first thing in the file. */
27#if defined (_AIX) && !defined (REGEX_MALLOC)
b8d8561b 28#pragma alloca
090089c4 29#endif
30
6637e3a5 31#ifndef _GNU_SOURCE
32#define _GNU_SOURCE 1
33#endif
090089c4 34
090089c4 35#include "config.h"
090089c4 36
1cf7b8fa 37#if !HAVE_ALLOCA
38#define REGEX_MALLOC 1
39#endif
40
090089c4 41/* We used to test for `BSTRING' here, but only GCC and Emacs define
b8d8561b 42 * `BSTRING', as far as I know, and neither of them use this code. */
090089c4 43#if HAVE_STRING_H || STDC_HEADERS
44#include <string.h>
090089c4 45#else
46#include <strings.h>
47#endif
48
49#ifdef STDC_HEADERS
50#include <stdlib.h>
51#else
b8d8561b 52char *malloc();
53char *realloc();
090089c4 54#endif
55
56
57/* Define the syntax stuff for \<, \>, etc. */
58
59/* This must be nonzero for the wordchar and notwordchar pattern
b8d8561b 60 * commands in re_match_2. */
61#ifndef Sword
090089c4 62#define Sword 1
63#endif
64
65#ifdef SYNTAX_TABLE
66
67extern char *re_syntax_table;
68
69#else /* not SYNTAX_TABLE */
70
71/* How many characters in the character set. */
72#define CHAR_SET_SIZE 256
73
74static char re_syntax_table[CHAR_SET_SIZE];
75
76static void
862bc6c0 77init_syntax_once(void)
090089c4 78{
b8d8561b 79 register int c;
80 static int done = 0;
090089c4 81
b8d8561b 82 if (done)
83 return;
090089c4 84
25347664 85 memset(re_syntax_table, 0, sizeof re_syntax_table);
090089c4 86
b8d8561b 87 for (c = 'a'; c <= 'z'; c++)
88 re_syntax_table[c] = Sword;
090089c4 89
b8d8561b 90 for (c = 'A'; c <= 'Z'; c++)
91 re_syntax_table[c] = Sword;
090089c4 92
b8d8561b 93 for (c = '0'; c <= '9'; c++)
94 re_syntax_table[c] = Sword;
090089c4 95
b8d8561b 96 re_syntax_table['_'] = Sword;
090089c4 97
b8d8561b 98 done = 1;
090089c4 99}
100
101#endif /* not SYNTAX_TABLE */
102
103#define SYNTAX(c) re_syntax_table[c]
104
090089c4 105\f
106/* Get the interface, including the syntax bits. */
107#include "GNUregex.h"
108
35516333 109/* Compile a fastmap for the compiled pattern in BUFFER; used to
110 * accelerate searches. Return 0 if successful and -2 if was an
111 * internal error. */
112static int re_compile_fastmap _RE_ARGS((struct re_pattern_buffer * buffer));
113
114
115/* Search in the string STRING (with length LENGTH) for the pattern
116 * compiled into BUFFER. Start searching at position START, for RANGE
117 * characters. Return the starting position of the match, -1 for no
118 * match, or -2 for an internal error. Also return register
119 * information in REGS (if REGS and BUFFER->no_sub are nonzero). */
120static int re_search
121 _RE_ARGS((struct re_pattern_buffer * buffer, const char *string,
122 int length, int start, int range, struct re_registers * regs));
123
124
125/* Like `re_search', but search in the concatenation of STRING1 and
126 * STRING2. Also, stop searching at index START + STOP. */
127static int re_search_2
128 _RE_ARGS((struct re_pattern_buffer * buffer, const char *string1,
129 int length1, const char *string2, int length2,
130 int start, int range, struct re_registers * regs, int stop));
131
132
133/* Like `re_search_2', but return how many characters in STRING the regexp
134 * in BUFFER matched, starting at position START. */
135static int re_match_2
136 _RE_ARGS((struct re_pattern_buffer * buffer, const char *string1,
137 int length1, const char *string2, int length2,
138 int start, struct re_registers * regs, int stop));
139
140
090089c4 141/* isalpha etc. are used for the character classes. */
142#include <ctype.h>
143
144#ifndef isascii
145#define isascii(c) 1
146#endif
147
148#ifdef isblank
ec451a0f 149#define ISBLANK(c) (isascii ((unsigned char)c) && isblank ((unsigned char)c))
090089c4 150#else
151#define ISBLANK(c) ((c) == ' ' || (c) == '\t')
152#endif
153#ifdef isgraph
ec451a0f 154#define ISGRAPH(c) (isascii ((unsigned char)c) && isgraph ((unsigned char)c))
090089c4 155#else
ec451a0f 156#define ISGRAPH(c) (isascii ((unsigned char)c) && isprint ((unsigned char)c) && !isspace ((unsigned char)c))
090089c4 157#endif
158
ec451a0f 159#define ISPRINT(c) (isascii ((unsigned char)c) && isprint ((unsigned char)c))
160#define ISDIGIT(c) (isascii ((unsigned char)c) && isdigit ((unsigned char)c))
161#define ISALNUM(c) (isascii ((unsigned char)c) && isalnum ((unsigned char)c))
162#define ISALPHA(c) (isascii ((unsigned char)c) && isalpha ((unsigned char)c))
163#define ISCNTRL(c) (isascii ((unsigned char)c) && iscntrl ((unsigned char)c))
164#define ISLOWER(c) (isascii ((unsigned char)c) && islower ((unsigned char)c))
165#define ISPUNCT(c) (isascii ((unsigned char)c) && ispunct ((unsigned char)c))
166#define ISSPACE(c) (isascii ((unsigned char)c) && isspace ((unsigned char)c))
167#define ISUPPER(c) (isascii ((unsigned char)c) && isupper ((unsigned char)c))
168#define ISXDIGIT(c) (isascii ((unsigned char)c) && isxdigit ((unsigned char)c))
090089c4 169
170#ifndef NULL
171#define NULL 0
172#endif
173
174/* We remove any previous definition of `SIGN_EXTEND_CHAR',
b8d8561b 175 * since ours (we hope) works properly with all combinations of
176 * machines, compilers, `char' and `unsigned char' argument types.
177 * (Per Bothner suggested the basic approach.) */
090089c4 178#undef SIGN_EXTEND_CHAR
24382924 179#ifdef __STDC__
090089c4 180#define SIGN_EXTEND_CHAR(c) ((signed char) (c))
b8d8561b 181#else /* not __STDC__ */
090089c4 182/* As in Harbison and Steele. */
183#define SIGN_EXTEND_CHAR(c) ((((unsigned char) (c)) ^ 128) - 128)
184#endif
185\f
186/* Should we use malloc or alloca? If REGEX_MALLOC is not defined, we
b8d8561b 187 * use `alloca' instead of `malloc'. This is because using malloc in
188 * re_search* or re_match* could cause memory leaks when C-g is used in
189 * Emacs; also, malloc is slower and causes storage fragmentation. On
190 * the other hand, malloc is more portable, and easier to debug.
191 *
192 * Because we sometimes use alloca, some routines have to be macros,
193 * not functions -- `alloca'-allocated space disappears at the end of the
194 * function it is called in. */
090089c4 195
196#ifdef REGEX_MALLOC
197
198#define REGEX_ALLOCATE malloc
199#define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize)
200
201#else /* not REGEX_MALLOC */
202
203/* Emacs already defines alloca, sometimes. */
204#ifndef alloca
205
206/* Make alloca work the best possible way. */
207#ifdef __GNUC__
208#define alloca __builtin_alloca
209#else /* not __GNUC__ */
210#if HAVE_ALLOCA_H
211#include <alloca.h>
212#else /* not __GNUC__ or HAVE_ALLOCA_H */
b8d8561b 213#ifndef _AIX /* Already did AIX, up at the top. */
214char *alloca();
090089c4 215#endif /* not _AIX */
b8d8561b 216#endif /* not HAVE_ALLOCA_H */
090089c4 217#endif /* not __GNUC__ */
218
219#endif /* not alloca */
220
221#define REGEX_ALLOCATE alloca
222
223/* Assumes a `char *destination' variable. */
224#define REGEX_REALLOCATE(source, osize, nsize) \
225 (destination = (char *) alloca (nsize), \
25347664 226 xmemcpy (destination, source, osize), \
090089c4 227 destination)
228
229#endif /* not REGEX_MALLOC */
230
231
232/* True if `size1' is non-NULL and PTR is pointing anywhere inside
b8d8561b 233 * `string1' or just past its end. This works if PTR is NULL, which is
234 * a good thing. */
090089c4 235#define FIRST_STRING_P(ptr) \
236 (size1 && string1 <= (ptr) && (ptr) <= string1 + size1)
237
238/* (Re)Allocate N items of type T using malloc, or fail. */
239#define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t)))
240#define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t)))
241#define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t)))
242
b8d8561b 243#define BYTEWIDTH 8 /* In bits. */
090089c4 244
245#define STREQ(s1, s2) ((strcmp (s1, s2) == 0))
246
247#define MAX(a, b) ((a) > (b) ? (a) : (b))
248#define MIN(a, b) ((a) < (b) ? (a) : (b))
249
cc192b50 250#if !defined(__MINGW32__) /* MinGW defines boolean */
090089c4 251typedef char boolean;
cc192b50 252#endif
090089c4 253#define false 0
254#define true 1
255\f
256/* These are the command codes that appear in compiled regular
b8d8561b 257 * expressions. Some opcodes are followed by argument bytes. A
258 * command code can specify any interpretation whatsoever for its
259 * arguments. Zero bytes may appear in the compiled regular expression.
260 *
261 * The value of `exactn' is needed in search.c (search_buffer) in Emacs.
262 * So regex.h defines a symbol `RE_EXACTN_VALUE' to be 1; the value of
263 * `exactn' we use here must also be 1. */
264
265typedef enum {
266 no_op = 0,
267
268 /* Followed by one byte giving n, then by n literal bytes. */
269 exactn = 1,
270
271 /* Matches any (more or less) character. */
272 anychar,
273
274 /* Matches any one char belonging to specified set. First
275 * following byte is number of bitmap bytes. Then come bytes
276 * for a bitmap saying which chars are in. Bits in each byte
277 * are ordered low-bit-first. A character is in the set if its
278 * bit is 1. A character too large to have a bit in the map is
279 * automatically not in the set. */
280 charset,
281
282 /* Same parameters as charset, but match any character that is
283 * not one of those specified. */
284 charset_not,
285
286 /* Start remembering the text that is matched, for storing in a
287 * register. Followed by one byte with the register number, in
288 * the range 0 to one less than the pattern buffer's re_nsub
289 * field. Then followed by one byte with the number of groups
290 * inner to this one. (This last has to be part of the
291 * start_memory only because we need it in the on_failure_jump
292 * of re_match_2.) */
293 start_memory,
294
295 /* Stop remembering the text that is matched and store it in a
296 * memory register. Followed by one byte with the register
297 * number, in the range 0 to one less than `re_nsub' in the
298 * pattern buffer, and one byte with the number of inner groups,
299 * just like `start_memory'. (We need the number of inner
300 * groups here because we don't have any easy way of finding the
301 * corresponding start_memory when we're at a stop_memory.) */
302 stop_memory,
303
304 /* Match a duplicate of something remembered. Followed by one
305 * byte containing the register number. */
306 duplicate,
307
308 /* Fail unless at beginning of line. */
309 begline,
310
311 /* Fail unless at end of line. */
312 endline,
313
35516333 314 /* Succeeds if or at beginning of string to be matched. */
b8d8561b 315 begbuf,
316
317 /* Analogously, for end of buffer/string. */
318 endbuf,
319
320 /* Followed by two byte relative address to which to jump. */
321 jump,
322
323 /* Same as jump, but marks the end of an alternative. */
324 jump_past_alt,
325
326 /* Followed by two-byte relative address of place to resume at
327 * in case of failure. */
328 on_failure_jump,
329
330 /* Like on_failure_jump, but pushes a placeholder instead of the
331 * current string position when executed. */
332 on_failure_keep_string_jump,
333
334 /* Throw away latest failure point and then jump to following
335 * two-byte relative address. */
336 pop_failure_jump,
337
338 /* Change to pop_failure_jump if know won't have to backtrack to
339 * match; otherwise change to jump. This is used to jump
340 * back to the beginning of a repeat. If what follows this jump
341 * clearly won't match what the repeat does, such that we can be
342 * sure that there is no use backtracking out of repetitions
343 * already matched, then we change it to a pop_failure_jump.
344 * Followed by two-byte address. */
345 maybe_pop_jump,
346
347 /* Jump to following two-byte address, and push a dummy failure
348 * point. This failure point will be thrown away if an attempt
349 * is made to use it for a failure. A `+' construct makes this
350 * before the first repeat. Also used as an intermediary kind
351 * of jump when compiling an alternative. */
352 dummy_failure_jump,
353
354 /* Push a dummy failure point and continue. Used at the end of
355 * alternatives. */
356 push_dummy_failure,
357
358 /* Followed by two-byte relative address and two-byte number n.
359 * After matching N times, jump to the address upon failure. */
360 succeed_n,
361
362 /* Followed by two-byte relative address, and two-byte number n.
363 * Jump to the address N times, then fail. */
364 jump_n,
365
366 /* Set the following two-byte relative address to the
367 * subsequent two-byte number. The address *includes* the two
368 * bytes of number. */
369 set_number_at,
370
371 wordchar, /* Matches any word-constituent character. */
372 notwordchar, /* Matches any char that is not a word-constituent. */
373
374 wordbeg, /* Succeeds if at word beginning. */
375 wordend, /* Succeeds if at word end. */
376
377 wordbound, /* Succeeds if at a word boundary. */
378 notwordbound /* Succeeds if not at a word boundary. */
090089c4 379
090089c4 380} re_opcode_t;
381\f
382/* Common operations on the compiled pattern. */
383
384/* Store NUMBER in two contiguous bytes starting at DESTINATION. */
385
386#define STORE_NUMBER(destination, number) \
387 do { \
388 (destination)[0] = (number) & 0377; \
389 (destination)[1] = (number) >> 8; \
390 } while (0)
391
392/* Same as STORE_NUMBER, except increment DESTINATION to
b8d8561b 393 * the byte after where the number is stored. Therefore, DESTINATION
394 * must be an lvalue. */
090089c4 395
396#define STORE_NUMBER_AND_INCR(destination, number) \
397 do { \
398 STORE_NUMBER (destination, number); \
399 (destination) += 2; \
400 } while (0)
401
402/* Put into DESTINATION a number stored in two contiguous bytes starting
b8d8561b 403 * at SOURCE. */
090089c4 404
405#define EXTRACT_NUMBER(destination, source) \
406 do { \
407 (destination) = *(source) & 0377; \
408 (destination) += SIGN_EXTEND_CHAR (*((source) + 1)) << 8; \
409 } while (0)
410
411#ifdef DEBUG
412static void
b8d8561b 413extract_number(dest, source)
414 int *dest;
415 unsigned char *source;
090089c4 416{
b8d8561b 417 int temp = SIGN_EXTEND_CHAR(*(source + 1));
418 *dest = *source & 0377;
419 *dest += temp << 8;
090089c4 420}
421
b8d8561b 422#ifndef EXTRACT_MACROS /* To debug the macros. */
090089c4 423#undef EXTRACT_NUMBER
424#define EXTRACT_NUMBER(dest, src) extract_number (&dest, src)
425#endif /* not EXTRACT_MACROS */
426
427#endif /* DEBUG */
428
429/* Same as EXTRACT_NUMBER, except increment SOURCE to after the number.
b8d8561b 430 * SOURCE must be an lvalue. */
090089c4 431
432#define EXTRACT_NUMBER_AND_INCR(destination, source) \
433 do { \
434 EXTRACT_NUMBER (destination, source); \
435 (source) += 2; \
436 } while (0)
437
438#ifdef DEBUG
439static void
b8d8561b 440extract_number_and_incr(destination, source)
441 int *destination;
442 unsigned char **source;
443{
444 extract_number(destination, *source);
445 *source += 2;
090089c4 446}
447
448#ifndef EXTRACT_MACROS
449#undef EXTRACT_NUMBER_AND_INCR
450#define EXTRACT_NUMBER_AND_INCR(dest, src) \
451 extract_number_and_incr (&dest, &src)
452#endif /* not EXTRACT_MACROS */
453
454#endif /* DEBUG */
455\f
456/* If DEBUG is defined, Regex prints many voluminous messages about what
b8d8561b 457 * it is doing (if the variable `debug' is nonzero). If linked with the
458 * main program in `iregex.c', you can enter patterns and strings
459 * interactively. And if linked with the main program in `main.c' and
460 * the other test files, you can run the already-written tests. */
090089c4 461
462#ifdef DEBUG
463
464/* We use standard I/O for debugging. */
465#include <stdio.h>
466
467/* It is useful to test things that ``must'' be true when debugging. */
468#include <assert.h>
469
470static int debug = 0;
471
472#define DEBUG_STATEMENT(e) e
473#define DEBUG_PRINT1(x) if (debug) printf (x)
474#define DEBUG_PRINT2(x1, x2) if (debug) printf (x1, x2)
475#define DEBUG_PRINT3(x1, x2, x3) if (debug) printf (x1, x2, x3)
476#define DEBUG_PRINT4(x1, x2, x3, x4) if (debug) printf (x1, x2, x3, x4)
477#define DEBUG_PRINT_COMPILED_PATTERN(p, s, e) \
478 if (debug) print_partial_compiled_pattern (s, e)
479#define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2) \
480 if (debug) print_double_string (w, s1, sz1, s2, sz2)
481
482
b8d8561b 483extern void printchar();
090089c4 484
485/* Print the fastmap in human-readable form. */
486
487void
b8d8561b 488print_fastmap(fastmap)
489 char *fastmap;
090089c4 490{
b8d8561b 491 unsigned was_a_range = 0;
492 unsigned i = 0;
493
494 while (i < (1 << BYTEWIDTH)) {
495 if (fastmap[i++]) {
496 was_a_range = 0;
497 printchar(i - 1);
498 while (i < (1 << BYTEWIDTH) && fastmap[i]) {
499 was_a_range = 1;
500 i++;
501 }
502 if (was_a_range) {
503 printf("-");
504 printchar(i - 1);
505 }
506 }
090089c4 507 }
b8d8561b 508 putchar('\n');
090089c4 509}
510
511
512/* Print a compiled pattern string in human-readable form, starting at
b8d8561b 513 * the START pointer into it and ending just before the pointer END. */
090089c4 514
515void
b8d8561b 516print_partial_compiled_pattern(start, end)
517 unsigned char *start;
518 unsigned char *end;
090089c4 519{
b8d8561b 520 int mcnt, mcnt2;
521 unsigned char *p = start;
522 unsigned char *pend = end;
523
524 if (start == NULL) {
525 printf("(null)\n");
526 return;
090089c4 527 }
b8d8561b 528 /* Loop over pattern commands. */
529 while (p < pend) {
530 switch ((re_opcode_t) * p++) {
531 case no_op:
532 printf("/no_op");
533 break;
090089c4 534
535 case exactn:
b8d8561b 536 mcnt = *p++;
537 printf("/exactn/%d", mcnt);
538 do {
539 putchar('/');
540 printchar(*p++);
541 }
542 while (--mcnt);
543 break;
090089c4 544
545 case start_memory:
b8d8561b 546 mcnt = *p++;
547 printf("/start_memory/%d/%d", mcnt, *p++);
548 break;
090089c4 549
550 case stop_memory:
b8d8561b 551 mcnt = *p++;
552 printf("/stop_memory/%d/%d", mcnt, *p++);
553 break;
090089c4 554
555 case duplicate:
b8d8561b 556 printf("/duplicate/%d", *p++);
557 break;
090089c4 558
559 case anychar:
b8d8561b 560 printf("/anychar");
561 break;
090089c4 562
563 case charset:
b8d8561b 564 case charset_not:
565 {
566 register int c;
567
568 printf("/charset%s",
569 (re_opcode_t) * (p - 1) == charset_not ? "_not" : "");
570
571 assert(p + *p < pend);
572
573 for (c = 0; c < *p; c++) {
574 unsigned bit;
575 unsigned char map_byte = p[1 + c];
576
577 putchar('/');
578
579 for (bit = 0; bit < BYTEWIDTH; bit++)
580 if (map_byte & (1 << bit))
581 printchar(c * BYTEWIDTH + bit);
582 }
583 p += 1 + *p;
584 break;
585 }
090089c4 586
587 case begline:
b8d8561b 588 printf("/begline");
589 break;
090089c4 590
591 case endline:
b8d8561b 592 printf("/endline");
593 break;
090089c4 594
595 case on_failure_jump:
b8d8561b 596 extract_number_and_incr(&mcnt, &p);
597 printf("/on_failure_jump/0/%d", mcnt);
598 break;
090089c4 599
600 case on_failure_keep_string_jump:
b8d8561b 601 extract_number_and_incr(&mcnt, &p);
602 printf("/on_failure_keep_string_jump/0/%d", mcnt);
603 break;
090089c4 604
605 case dummy_failure_jump:
b8d8561b 606 extract_number_and_incr(&mcnt, &p);
607 printf("/dummy_failure_jump/0/%d", mcnt);
608 break;
090089c4 609
610 case push_dummy_failure:
b8d8561b 611 printf("/push_dummy_failure");
612 break;
613
614 case maybe_pop_jump:
615 extract_number_and_incr(&mcnt, &p);
616 printf("/maybe_pop_jump/0/%d", mcnt);
617 break;
618
619 case pop_failure_jump:
620 extract_number_and_incr(&mcnt, &p);
621 printf("/pop_failure_jump/0/%d", mcnt);
622 break;
623
624 case jump_past_alt:
625 extract_number_and_incr(&mcnt, &p);
626 printf("/jump_past_alt/0/%d", mcnt);
627 break;
628
629 case jump:
630 extract_number_and_incr(&mcnt, &p);
631 printf("/jump/0/%d", mcnt);
632 break;
633
634 case succeed_n:
635 extract_number_and_incr(&mcnt, &p);
636 extract_number_and_incr(&mcnt2, &p);
637 printf("/succeed_n/0/%d/0/%d", mcnt, mcnt2);
638 break;
639
640 case jump_n:
641 extract_number_and_incr(&mcnt, &p);
642 extract_number_and_incr(&mcnt2, &p);
643 printf("/jump_n/0/%d/0/%d", mcnt, mcnt2);
644 break;
645
646 case set_number_at:
647 extract_number_and_incr(&mcnt, &p);
648 extract_number_and_incr(&mcnt2, &p);
649 printf("/set_number_at/0/%d/0/%d", mcnt, mcnt2);
650 break;
651
652 case wordbound:
653 printf("/wordbound");
654 break;
090089c4 655
656 case notwordbound:
b8d8561b 657 printf("/notwordbound");
658 break;
090089c4 659
660 case wordbeg:
b8d8561b 661 printf("/wordbeg");
662 break;
663
090089c4 664 case wordend:
b8d8561b 665 printf("/wordend");
666
090089c4 667 case wordchar:
b8d8561b 668 printf("/wordchar");
669 break;
670
090089c4 671 case notwordchar:
b8d8561b 672 printf("/notwordchar");
673 break;
090089c4 674
675 case begbuf:
b8d8561b 676 printf("/begbuf");
677 break;
090089c4 678
679 case endbuf:
b8d8561b 680 printf("/endbuf");
681 break;
090089c4 682
b8d8561b 683 default:
684 printf("?%d", *(p - 1));
090089c4 685 }
686 }
b8d8561b 687 printf("/\n");
090089c4 688}
689
690
691void
b8d8561b 692print_compiled_pattern(bufp)
693 struct re_pattern_buffer *bufp;
090089c4 694{
b8d8561b 695 unsigned char *buffer = bufp->buffer;
090089c4 696
b8d8561b 697 print_partial_compiled_pattern(buffer, buffer + bufp->used);
698 printf("%d bytes used/%d bytes allocated.\n", bufp->used, bufp->allocated);
090089c4 699
b8d8561b 700 if (bufp->fastmap_accurate && bufp->fastmap) {
701 printf("fastmap: ");
702 print_fastmap(bufp->fastmap);
090089c4 703 }
b8d8561b 704 printf("re_nsub: %d\t", bufp->re_nsub);
705 printf("regs_alloc: %d\t", bufp->regs_allocated);
706 printf("can_be_null: %d\t", bufp->can_be_null);
707 printf("newline_anchor: %d\n", bufp->newline_anchor);
708 printf("no_sub: %d\t", bufp->no_sub);
709 printf("not_bol: %d\t", bufp->not_bol);
710 printf("not_eol: %d\t", bufp->not_eol);
711 printf("syntax: %d\n", bufp->syntax);
712 /* Perhaps we should print the translate table? */
090089c4 713}
714
715
716void
b8d8561b 717print_double_string(where, string1, size1, string2, size2)
718 const char *where;
719 const char *string1;
720 const char *string2;
721 int size1;
722 int size2;
090089c4 723{
b8d8561b 724 unsigned this_char;
725
726 if (where == NULL)
727 printf("(null)");
728 else {
729 if (FIRST_STRING_P(where)) {
730 for (this_char = where - string1; this_char < size1; this_char++)
731 printchar(string1[this_char]);
732
733 where = string2;
734 }
735 for (this_char = where - string2; this_char < size2; this_char++)
736 printchar(string2[this_char]);
090089c4 737 }
738}
739
740#else /* not DEBUG */
741
742#undef assert
743#define assert(e)
744
745#define DEBUG_STATEMENT(e)
746#define DEBUG_PRINT1(x)
747#define DEBUG_PRINT2(x1, x2)
748#define DEBUG_PRINT3(x1, x2, x3)
749#define DEBUG_PRINT4(x1, x2, x3, x4)
750#define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)
751#define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)
752
753#endif /* not DEBUG */
754\f
090089c4 755/* This table gives an error message for each of the error codes listed
b8d8561b 756 * in regex.h. Obviously the order here has to be same as there. */
090089c4 757
758static const char *re_error_msg[] =
b8d8561b 759{NULL, /* REG_NOERROR */
760 "No match", /* REG_NOMATCH */
761 "Invalid regular expression", /* REG_BADPAT */
762 "Invalid collation character", /* REG_ECOLLATE */
763 "Invalid character class name", /* REG_ECTYPE */
764 "Trailing backslash", /* REG_EESCAPE */
765 "Invalid back reference", /* REG_ESUBREG */
766 "Unmatched [ or [^", /* REG_EBRACK */
767 "Unmatched ( or \\(", /* REG_EPAREN */
768 "Unmatched \\{", /* REG_EBRACE */
769 "Invalid content of \\{\\}", /* REG_BADBR */
770 "Invalid range end", /* REG_ERANGE */
771 "Memory exhausted", /* REG_ESPACE */
090089c4 772 "Invalid preceding regular expression", /* REG_BADRPT */
773 "Premature end of regular expression", /* REG_EEND */
b8d8561b 774 "Regular expression too big", /* REG_ESIZE */
775 "Unmatched ) or \\)", /* REG_ERPAREN */
776};
090089c4 777\f
778/* Subroutine declarations and macros for regex_compile. */
779
090089c4 780/* Fetch the next character in the uncompiled pattern---translating it
b8d8561b 781 * if necessary. Also cast from a signed character in the constant
782 * string passed to us by the user to an unsigned char that we can use
783 * as an array index (in, e.g., `translate'). */
090089c4 784#define PATFETCH(c) \
785 do {if (p == pend) return REG_EEND; \
786 c = (unsigned char) *p++; \
787 if (translate) c = translate[c]; \
788 } while (0)
789
790/* Fetch the next character in the uncompiled pattern, with no
b8d8561b 791 * translation. */
090089c4 792#define PATFETCH_RAW(c) \
793 do {if (p == pend) return REG_EEND; \
794 c = (unsigned char) *p++; \
795 } while (0)
796
797/* Go backwards one character in the pattern. */
798#define PATUNFETCH p--
799
800
801/* If `translate' is non-null, return translate[D], else just D. We
b8d8561b 802 * cast the subscript to translate because some data is declared as
803 * `char *', to avoid warnings when a string constant is passed. But
804 * when we use a character as a subscript we must make it unsigned. */
090089c4 805#define TRANSLATE(d) (translate ? translate[(unsigned char) (d)] : (d))
806
807
808/* Macros for outputting the compiled pattern into `buffer'. */
809
810/* If the buffer isn't allocated when it comes in, use this. */
811#define INIT_BUF_SIZE 32
812
813/* Make sure we have at least N more bytes of space in buffer. */
814#define GET_BUFFER_SPACE(n) \
815 while (b - bufp->buffer + (n) > bufp->allocated) \
816 EXTEND_BUFFER ()
817
818/* Make sure we have one more byte of buffer space and then add C to it. */
819#define BUF_PUSH(c) \
820 do { \
821 GET_BUFFER_SPACE (1); \
822 *b++ = (unsigned char) (c); \
823 } while (0)
824
825
826/* Ensure we have two more bytes of buffer space and then append C1 and C2. */
827#define BUF_PUSH_2(c1, c2) \
828 do { \
829 GET_BUFFER_SPACE (2); \
830 *b++ = (unsigned char) (c1); \
831 *b++ = (unsigned char) (c2); \
832 } while (0)
833
834
835/* As with BUF_PUSH_2, except for three bytes. */
836#define BUF_PUSH_3(c1, c2, c3) \
837 do { \
838 GET_BUFFER_SPACE (3); \
839 *b++ = (unsigned char) (c1); \
840 *b++ = (unsigned char) (c2); \
841 *b++ = (unsigned char) (c3); \
842 } while (0)
843
844
845/* Store a jump with opcode OP at LOC to location TO. We store a
b8d8561b 846 * relative address offset by the three bytes the jump itself occupies. */
090089c4 847#define STORE_JUMP(op, loc, to) \
848 store_op1 (op, loc, (to) - (loc) - 3)
849
850/* Likewise, for a two-argument jump. */
851#define STORE_JUMP2(op, loc, to, arg) \
852 store_op2 (op, loc, (to) - (loc) - 3, arg)
853
854/* Like `STORE_JUMP', but for inserting. Assume `b' is the buffer end. */
855#define INSERT_JUMP(op, loc, to) \
856 insert_op1 (op, loc, (to) - (loc) - 3, b)
857
858/* Like `STORE_JUMP2', but for inserting. Assume `b' is the buffer end. */
859#define INSERT_JUMP2(op, loc, to, arg) \
860 insert_op2 (op, loc, (to) - (loc) - 3, arg, b)
861
862
863/* This is not an arbitrary limit: the arguments which represent offsets
b8d8561b 864 * into the pattern are two bytes long. So if 2^16 bytes turns out to
865 * be too small, many things would have to change. */
090089c4 866#define MAX_BUF_SIZE (1L << 16)
867
868
869/* Extend the buffer by twice its current size via realloc and
b8d8561b 870 * reset the pointers that pointed into the old block to point to the
871 * correct places in the new one. If extending the buffer results in it
872 * being larger than MAX_BUF_SIZE, then flag memory exhausted. */
090089c4 873#define EXTEND_BUFFER() \
874 do { \
875 unsigned char *old_buffer = bufp->buffer; \
876 if (bufp->allocated == MAX_BUF_SIZE) \
877 return REG_ESIZE; \
878 bufp->allocated <<= 1; \
879 if (bufp->allocated > MAX_BUF_SIZE) \
880 bufp->allocated = MAX_BUF_SIZE; \
881 bufp->buffer = (unsigned char *) realloc (bufp->buffer, bufp->allocated);\
882 if (bufp->buffer == NULL) \
883 return REG_ESPACE; \
884 /* If the buffer moved, move all the pointers into it. */ \
885 if (old_buffer != bufp->buffer) \
886 { \
887 b = (b - old_buffer) + bufp->buffer; \
888 begalt = (begalt - old_buffer) + bufp->buffer; \
889 if (fixup_alt_jump) \
890 fixup_alt_jump = (fixup_alt_jump - old_buffer) + bufp->buffer;\
891 if (laststart) \
892 laststart = (laststart - old_buffer) + bufp->buffer; \
893 if (pending_exact) \
894 pending_exact = (pending_exact - old_buffer) + bufp->buffer; \
895 } \
896 } while (0)
897
898
899/* Since we have one byte reserved for the register number argument to
b8d8561b 900 * {start,stop}_memory, the maximum number of groups we can report
901 * things about is what fits in that byte. */
090089c4 902#define MAX_REGNUM 255
903
904/* But patterns can have more than `MAX_REGNUM' registers. We just
b8d8561b 905 * ignore the excess. */
090089c4 906typedef unsigned regnum_t;
907
908
909/* Macros for the compile stack. */
910
911/* Since offsets can go either forwards or backwards, this type needs to
b8d8561b 912 * be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1. */
090089c4 913typedef int pattern_offset_t;
914
b8d8561b 915typedef struct {
916 pattern_offset_t begalt_offset;
917 pattern_offset_t fixup_alt_jump;
918 pattern_offset_t inner_group_offset;
919 pattern_offset_t laststart_offset;
920 regnum_t regnum;
090089c4 921} compile_stack_elt_t;
922
923
b8d8561b 924typedef struct {
925 compile_stack_elt_t *stack;
926 unsigned size;
927 unsigned avail; /* Offset of next open position. */
090089c4 928} compile_stack_type;
929
862bc6c0 930static void store_op1(re_opcode_t op, unsigned char *loc, int arg);
931static void store_op2( re_opcode_t op, unsigned char *loc, int arg1, int arg2);
932static void insert_op1(re_opcode_t op, unsigned char *loc, int arg, unsigned char *end);
933static void insert_op2(re_opcode_t op, unsigned char *loc, int arg1, int arg2, unsigned char *end);
934static boolean at_begline_loc_p(const char * pattern, const char *p, reg_syntax_t syntax);
935static boolean at_endline_loc_p(const char *p, const char *pend, int syntax);
936static boolean group_in_compile_stack(compile_stack_type compile_stack, regnum_t regnum);
937static reg_errcode_t compile_range(const char **p_ptr, const char *pend, char *translate, reg_syntax_t syntax, unsigned char *b);
090089c4 938
939#define INIT_COMPILE_STACK_SIZE 32
940
941#define COMPILE_STACK_EMPTY (compile_stack.avail == 0)
942#define COMPILE_STACK_FULL (compile_stack.avail == compile_stack.size)
943
944/* The next available element. */
945#define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
946
947
948/* Set the bit for character C in a list. */
949#define SET_LIST_BIT(c) \
950 (b[((unsigned char) (c)) / BYTEWIDTH] \
951 |= 1 << (((unsigned char) c) % BYTEWIDTH))
952
953
954/* Get the next unsigned number in the uncompiled pattern. */
955#define GET_UNSIGNED_NUMBER(num) \
956 { if (p != pend) \
957 { \
958 PATFETCH (c); \
959 while (ISDIGIT (c)) \
960 { \
961 if (num < 0) \
962 num = 0; \
963 num = num * 10 + c - '0'; \
964 if (p == pend) \
965 break; \
966 PATFETCH (c); \
967 } \
968 } \
b8d8561b 969 }
090089c4 970
b8d8561b 971#define CHAR_CLASS_MAX_LENGTH 6 /* Namely, `xdigit'. */
090089c4 972
973#define IS_CHAR_CLASS(string) \
974 (STREQ (string, "alpha") || STREQ (string, "upper") \
975 || STREQ (string, "lower") || STREQ (string, "digit") \
976 || STREQ (string, "alnum") || STREQ (string, "xdigit") \
977 || STREQ (string, "space") || STREQ (string, "print") \
978 || STREQ (string, "punct") || STREQ (string, "graph") \
979 || STREQ (string, "cntrl") || STREQ (string, "blank"))
980\f
981/* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
b8d8561b 982 * Returns one of error codes defined in `regex.h', or zero for success.
983 *
984 * Assumes the `allocated' (and perhaps `buffer') and `translate'
985 * fields are set in BUFP on entry.
986 *
987 * If it succeeds, results are put in BUFP (if it returns an error, the
988 * contents of BUFP are undefined):
989 * `buffer' is the compiled pattern;
990 * `syntax' is set to SYNTAX;
991 * `used' is set to the length of the compiled pattern;
992 * `fastmap_accurate' is zero;
993 * `re_nsub' is the number of subexpressions in PATTERN;
994 * `not_bol' and `not_eol' are zero;
995 *
996 * The `fastmap' and `newline_anchor' fields are neither
997 * examined nor set. */
090089c4 998
999static reg_errcode_t
862bc6c0 1000regex_compile(const char *pattern, int size, reg_syntax_t syntax, struct re_pattern_buffer *bufp)
090089c4 1001{
b8d8561b 1002 /* We fetch characters from PATTERN here. Even though PATTERN is
1003 * `char *' (i.e., signed), we declare these variables as unsigned, so
1004 * they can be reliably used as array indices. */
1005 register unsigned char c, c1;
1006
1007 /* A random tempory spot in PATTERN. */
1008 const char *p1;
1009
1010 /* Points to the end of the buffer, where we should append. */
1011 register unsigned char *b;
1012
1013 /* Keeps track of unclosed groups. */
1014 compile_stack_type compile_stack;
1015
1016 /* Points to the current (ending) position in the pattern. */
1017 const char *p = pattern;
1018 const char *pend = pattern + size;
1019
1020 /* How to translate the characters in the pattern. */
1021 char *translate = bufp->translate;
1022
1023 /* Address of the count-byte of the most recently inserted `exactn'
1024 * command. This makes it possible to tell if a new exact-match
1025 * character can be added to that command or if the character requires
1026 * a new `exactn' command. */
1027 unsigned char *pending_exact = 0;
1028
1029 /* Address of start of the most recently finished expression.
1030 * This tells, e.g., postfix * where to find the start of its
1031 * operand. Reset at the beginning of groups and alternatives. */
1032 unsigned char *laststart = 0;
1033
1034 /* Address of beginning of regexp, or inside of last group. */
1035 unsigned char *begalt;
1036
1037 /* Place in the uncompiled pattern (i.e., the {) to
1038 * which to go back if the interval is invalid. */
1039 const char *beg_interval;
1040
1041 /* Address of the place where a forward jump should go to the end of
1042 * the containing expression. Each alternative of an `or' -- except the
1043 * last -- ends with a forward jump of this sort. */
1044 unsigned char *fixup_alt_jump = 0;
1045
1046 /* Counts open-groups as they are encountered. Remembered for the
1047 * matching close-group on the compile stack, so the same register
1048 * number is put in the stop_memory as the start_memory. */
1049 regnum_t regnum = 0;
090089c4 1050
1051#ifdef DEBUG
b8d8561b 1052 DEBUG_PRINT1("\nCompiling pattern: ");
1053 if (debug) {
1054 unsigned debug_count;
1055
1056 for (debug_count = 0; debug_count < size; debug_count++)
1057 printchar(pattern[debug_count]);
1058 putchar('\n');
090089c4 1059 }
1060#endif /* DEBUG */
1061
b8d8561b 1062 /* Initialize the compile stack. */
1063 compile_stack.stack = TALLOC(INIT_COMPILE_STACK_SIZE, compile_stack_elt_t);
1064 if (compile_stack.stack == NULL)
1065 return REG_ESPACE;
090089c4 1066
b8d8561b 1067 compile_stack.size = INIT_COMPILE_STACK_SIZE;
1068 compile_stack.avail = 0;
090089c4 1069
b8d8561b 1070 /* Initialize the pattern buffer. */
1071 bufp->syntax = syntax;
1072 bufp->fastmap_accurate = 0;
1073 bufp->not_bol = bufp->not_eol = 0;
090089c4 1074
b8d8561b 1075 /* Set `used' to zero, so that if we return an error, the pattern
1076 * printer (for debugging) will think there's no pattern. We reset it
1077 * at the end. */
1078 bufp->used = 0;
1079
1080 /* Always count groups, whether or not bufp->no_sub is set. */
1081 bufp->re_nsub = 0;
090089c4 1082
35516333 1083#if !defined (SYNTAX_TABLE)
b8d8561b 1084 /* Initialize the syntax table. */
1085 init_syntax_once();
090089c4 1086#endif
1087
b8d8561b 1088 if (bufp->allocated == 0) {
1089 if (bufp->buffer) { /* If zero allocated, but buffer is non-null, try to realloc
1090 * enough space. This loses if buffer's address is bogus, but
1091 * that is the user's responsibility. */
1092 RETALLOC(bufp->buffer, INIT_BUF_SIZE, unsigned char);
1093 } else { /* Caller did not allocate a buffer. Do it for them. */
1094 bufp->buffer = TALLOC(INIT_BUF_SIZE, unsigned char);
1095 }
1096 if (!bufp->buffer)
1097 return REG_ESPACE;
1098
1099 bufp->allocated = INIT_BUF_SIZE;
090089c4 1100 }
b8d8561b 1101 begalt = b = bufp->buffer;
090089c4 1102
b8d8561b 1103 /* Loop through the uncompiled pattern until we're at the end. */
1104 while (p != pend) {
1105 PATFETCH(c);
1106
1107 switch (c) {
1108 case '^':
1109 {
1110 if ( /* If at start of pattern, it's an operator. */
1111 p == pattern + 1
1112 /* If context independent, it's an operator. */
1113 || syntax & RE_CONTEXT_INDEP_ANCHORS
1114 /* Otherwise, depends on what's come before. */
1115 || at_begline_loc_p(pattern, p, syntax))
1116 BUF_PUSH(begline);
1117 else
1118 goto normal_char;
1119 }
1120 break;
1121
1122
1123 case '$':
1124 {
1125 if ( /* If at end of pattern, it's an operator. */
1126 p == pend
1127 /* If context independent, it's an operator. */
1128 || syntax & RE_CONTEXT_INDEP_ANCHORS
1129 /* Otherwise, depends on what's next. */
1130 || at_endline_loc_p(p, pend, syntax))
1131 BUF_PUSH(endline);
1132 else
1133 goto normal_char;
1134 }
1135 break;
090089c4 1136
1137
1138 case '+':
b8d8561b 1139 case '?':
1140 if ((syntax & RE_BK_PLUS_QM)
1141 || (syntax & RE_LIMITED_OPS))
1142 goto normal_char;
1143 handle_plus:
1144 case '*':
1145 /* If there is no previous pattern... */
1146 if (!laststart) {
1147 if (syntax & RE_CONTEXT_INVALID_OPS)
1148 return REG_BADRPT;
1149 else if (!(syntax & RE_CONTEXT_INDEP_OPS))
1150 goto normal_char;
1151 } {
1152 /* Are we optimizing this jump? */
1153 boolean keep_string_p = false;
1154
1155 /* 1 means zero (many) matches is allowed. */
1156 char zero_times_ok = 0, many_times_ok = 0;
1157
1158 /* If there is a sequence of repetition chars, collapse it
1159 * down to just one (the right one). We can't combine
1160 * interval operators with these because of, e.g., `a{2}*',
1161 * which should only match an even number of `a's. */
1162
1163 for (;;) {
1164 zero_times_ok |= c != '+';
1165 many_times_ok |= c != '?';
1166
1167 if (p == pend)
1168 break;
1169
1170 PATFETCH(c);
1171
1172 if (c == '*'
1173 || (!(syntax & RE_BK_PLUS_QM) && (c == '+' || c == '?')));
1174
1175 else if (syntax & RE_BK_PLUS_QM && c == '\\') {
1176 if (p == pend)
1177 return REG_EESCAPE;
1178
1179 PATFETCH(c1);
1180 if (!(c1 == '+' || c1 == '?')) {
1181 PATUNFETCH;
1182 PATUNFETCH;
1183 break;
1184 }
1185 c = c1;
1186 } else {
1187 PATUNFETCH;
1188 break;
1189 }
1190
1191 /* If we get here, we found another repeat character. */
1192 }
1193
1194 /* Star, etc. applied to an empty pattern is equivalent
1195 * to an empty pattern. */
1196 if (!laststart)
1197 break;
1198
1199 /* Now we know whether or not zero matches is allowed
1200 * and also whether or not two or more matches is allowed. */
1201 if (many_times_ok) { /* More than one repetition is allowed, so put in at the
1202 * end a backward relative jump from `b' to before the next
1203 * jump we're going to put in below (which jumps from
1204 * laststart to after this jump).
1205 *
1206 * But if we are at the `*' in the exact sequence `.*\n',
1207 * insert an unconditional jump backwards to the .,
1208 * instead of the beginning of the loop. This way we only
1209 * push a failure point once, instead of every time
1210 * through the loop. */
1211 assert(p - 1 > pattern);
1212
1213 /* Allocate the space for the jump. */
1214 GET_BUFFER_SPACE(3);
1215
1216 /* We know we are not at the first character of the pattern,
1217 * because laststart was nonzero. And we've already
1218 * incremented `p', by the way, to be the character after
1219 * the `*'. Do we have to do something analogous here
1220 * for null bytes, because of RE_DOT_NOT_NULL? */
1221 if (TRANSLATE(*(p - 2)) == TRANSLATE('.')
1222 && zero_times_ok
1223 && p < pend && TRANSLATE(*p) == TRANSLATE('\n')
1224 && !(syntax & RE_DOT_NEWLINE)) { /* We have .*\n. */
1225 STORE_JUMP(jump, b, laststart);
1226 keep_string_p = true;
1227 } else
1228 /* Anything else. */
1229 STORE_JUMP(maybe_pop_jump, b, laststart - 3);
1230
1231 /* We've added more stuff to the buffer. */
1232 b += 3;
1233 }
1234 /* On failure, jump from laststart to b + 3, which will be the
1235 * end of the buffer after this jump is inserted. */
1236 GET_BUFFER_SPACE(3);
1237 INSERT_JUMP(keep_string_p ? on_failure_keep_string_jump
1238 : on_failure_jump,
1239 laststart, b + 3);
1240 pending_exact = 0;
1241 b += 3;
1242
1243 if (!zero_times_ok) {
1244 /* At least one repetition is required, so insert a
1245 * `dummy_failure_jump' before the initial
1246 * `on_failure_jump' instruction of the loop. This
1247 * effects a skip over that instruction the first time
1248 * we hit that loop. */
1249 GET_BUFFER_SPACE(3);
1250 INSERT_JUMP(dummy_failure_jump, laststart, laststart + 6);
1251 b += 3;
1252 }
1253 }
1254 break;
090089c4 1255
1256
1257 case '.':
b8d8561b 1258 laststart = b;
1259 BUF_PUSH(anychar);
1260 break;
1261
1262
1263 case '[':
1264 {
1265 boolean had_char_class = false;
1266
1267 if (p == pend)
1268 return REG_EBRACK;
1269
1270 /* Ensure that we have enough space to push a charset: the
1271 * opcode, the length count, and the bitset; 34 bytes in all. */
1272 GET_BUFFER_SPACE(34);
1273
1274 laststart = b;
1275
1276 /* We test `*p == '^' twice, instead of using an if
1277 * statement, so we only need one BUF_PUSH. */
1278 BUF_PUSH(*p == '^' ? charset_not : charset);
1279 if (*p == '^')
1280 p++;
1281
1282 /* Remember the first position in the bracket expression. */
1283 p1 = p;
1284
1285 /* Push the number of bytes in the bitmap. */
1286 BUF_PUSH((1 << BYTEWIDTH) / BYTEWIDTH);
1287
1288 /* Clear the whole map. */
25347664 1289 memset(b, 0, (1 << BYTEWIDTH) / BYTEWIDTH);
b8d8561b 1290
1291 /* charset_not matches newline according to a syntax bit. */
1292 if ((re_opcode_t) b[-2] == charset_not
1293 && (syntax & RE_HAT_LISTS_NOT_NEWLINE))
1294 SET_LIST_BIT('\n');
1295
1296 /* Read in characters and ranges, setting map bits. */
1297 for (;;) {
1298 if (p == pend)
1299 return REG_EBRACK;
1300
1301 PATFETCH(c);
1302
1303 /* \ might escape characters inside [...] and [^...]. */
1304 if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\') {
1305 if (p == pend)
1306 return REG_EESCAPE;
1307
1308 PATFETCH(c1);
1309 SET_LIST_BIT(c1);
1310 continue;
1311 }
1312 /* Could be the end of the bracket expression. If it's
1313 * not (i.e., when the bracket expression is `[]' so
1314 * far), the ']' character bit gets set way below. */
1315 if (c == ']' && p != p1 + 1)
1316 break;
1317
1318 /* Look ahead to see if it's a range when the last thing
1319 * was a character class. */
1320 if (had_char_class && c == '-' && *p != ']')
1321 return REG_ERANGE;
1322
1323 /* Look ahead to see if it's a range when the last thing
1324 * was a character: if this is a hyphen not at the
1325 * beginning or the end of a list, then it's the range
1326 * operator. */
1327 if (c == '-'
1328 && !(p - 2 >= pattern && p[-2] == '[')
1329 && !(p - 3 >= pattern && p[-3] == '[' && p[-2] == '^')
1330 && *p != ']') {
1331 reg_errcode_t ret
1332 = compile_range(&p, pend, translate, syntax, b);
1333 if (ret != REG_NOERROR)
1334 return ret;
1335 } else if (p[0] == '-' && p[1] != ']') { /* This handles ranges made up of characters only. */
1336 reg_errcode_t ret;
1337
1338 /* Move past the `-'. */
1339 PATFETCH(c1);
1340
1341 ret = compile_range(&p, pend, translate, syntax, b);
1342 if (ret != REG_NOERROR)
1343 return ret;
1344 }
1345 /* See if we're at the beginning of a possible character
1346 * class. */
1347
1348 else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == ':') { /* Leave room for the null. */
1349 char str[CHAR_CLASS_MAX_LENGTH + 1];
1350
1351 PATFETCH(c);
1352 c1 = 0;
1353
1354 /* If pattern is `[[:'. */
1355 if (p == pend)
1356 return REG_EBRACK;
1357
1358 for (;;) {
1359 PATFETCH(c);
1360 if (c == ':' || c == ']' || p == pend
1361 || c1 == CHAR_CLASS_MAX_LENGTH)
1362 break;
1363 str[c1++] = c;
1364 }
1365 str[c1] = '\0';
1366
1367 /* If isn't a word bracketed by `[:' and:`]':
1368 * undo the ending character, the letters, and leave
1369 * the leading `:' and `[' (but set bits for them). */
1370 if (c == ':' && *p == ']') {
1371 int ch;
1372 boolean is_alnum = STREQ(str, "alnum");
1373 boolean is_alpha = STREQ(str, "alpha");
1374 boolean is_blank = STREQ(str, "blank");
1375 boolean is_cntrl = STREQ(str, "cntrl");
1376 boolean is_digit = STREQ(str, "digit");
1377 boolean is_graph = STREQ(str, "graph");
1378 boolean is_lower = STREQ(str, "lower");
1379 boolean is_print = STREQ(str, "print");
1380 boolean is_punct = STREQ(str, "punct");
1381 boolean is_space = STREQ(str, "space");
1382 boolean is_upper = STREQ(str, "upper");
1383 boolean is_xdigit = STREQ(str, "xdigit");
1384
1385 if (!IS_CHAR_CLASS(str))
1386 return REG_ECTYPE;
1387
1388 /* Throw away the ] at the end of the character
1389 * class. */
1390 PATFETCH(c);
1391
1392 if (p == pend)
1393 return REG_EBRACK;
1394
1395 for (ch = 0; ch < 1 << BYTEWIDTH; ch++) {
1396 if ((is_alnum && ISALNUM(ch))
1397 || (is_alpha && ISALPHA(ch))
1398 || (is_blank && ISBLANK(ch))
1399 || (is_cntrl && ISCNTRL(ch))
1400 || (is_digit && ISDIGIT(ch))
1401 || (is_graph && ISGRAPH(ch))
1402 || (is_lower && ISLOWER(ch))
1403 || (is_print && ISPRINT(ch))
1404 || (is_punct && ISPUNCT(ch))
1405 || (is_space && ISSPACE(ch))
1406 || (is_upper && ISUPPER(ch))
1407 || (is_xdigit && ISXDIGIT(ch)))
1408 SET_LIST_BIT(ch);
1409 }
1410 had_char_class = true;
1411 } else {
1412 c1++;
1413 while (c1--)
1414 PATUNFETCH;
1415 SET_LIST_BIT('[');
1416 SET_LIST_BIT(':');
1417 had_char_class = false;
1418 }
1419 } else {
1420 had_char_class = false;
1421 SET_LIST_BIT(c);
1422 }
1423 }
1424
1425 /* Discard any (non)matching list bytes that are all 0 at the
1426 * end of the map. Decrease the map-length byte too. */
1427 while ((int) b[-1] > 0 && b[b[-1] - 1] == 0)
1428 b[-1]--;
1429 b += b[-1];
1430 }
1431 break;
090089c4 1432
1433
1434 case '(':
b8d8561b 1435 if (syntax & RE_NO_BK_PARENS)
1436 goto handle_open;
1437 else
1438 goto normal_char;
090089c4 1439
1440
b8d8561b 1441 case ')':
1442 if (syntax & RE_NO_BK_PARENS)
1443 goto handle_close;
1444 else
1445 goto normal_char;
090089c4 1446
1447
b8d8561b 1448 case '\n':
1449 if (syntax & RE_NEWLINE_ALT)
1450 goto handle_alt;
1451 else
1452 goto normal_char;
090089c4 1453
1454
1455 case '|':
b8d8561b 1456 if (syntax & RE_NO_BK_VBAR)
1457 goto handle_alt;
1458 else
1459 goto normal_char;
1460
1461
1462 case '{':
1463 if (syntax & RE_INTERVALS && syntax & RE_NO_BK_BRACES)
1464 goto handle_interval;
1465 else
1466 goto normal_char;
1467
1468
1469 case '\\':
1470 if (p == pend)
1471 return REG_EESCAPE;
1472
1473 /* Do not translate the character after the \, so that we can
1474 * distinguish, e.g., \B from \b, even if we normally would
1475 * translate, e.g., B to b. */
1476 PATFETCH_RAW(c);
1477
1478 switch (c) {
1479 case '(':
1480 if (syntax & RE_NO_BK_PARENS)
1481 goto normal_backslash;
1482
1483 handle_open:
1484 bufp->re_nsub++;
1485 regnum++;
1486
1487 if (COMPILE_STACK_FULL) {
1488 RETALLOC(compile_stack.stack, compile_stack.size << 1,
1489 compile_stack_elt_t);
1490 if (compile_stack.stack == NULL)
1491 return REG_ESPACE;
1492
1493 compile_stack.size <<= 1;
1494 }
1495 /* These are the values to restore when we hit end of this
1496 * group. They are all relative offsets, so that if the
1497 * whole pattern moves because of realloc, they will still
1498 * be valid. */
1499 COMPILE_STACK_TOP.begalt_offset = begalt - bufp->buffer;
1500 COMPILE_STACK_TOP.fixup_alt_jump
1501 = fixup_alt_jump ? fixup_alt_jump - bufp->buffer + 1 : 0;
1502 COMPILE_STACK_TOP.laststart_offset = b - bufp->buffer;
1503 COMPILE_STACK_TOP.regnum = regnum;
1504
1505 /* We will eventually replace the 0 with the number of
1506 * groups inner to this one. But do not push a
1507 * start_memory for groups beyond the last one we can
1508 * represent in the compiled pattern. */
1509 if (regnum <= MAX_REGNUM) {
1510 COMPILE_STACK_TOP.inner_group_offset = b - bufp->buffer + 2;
1511 BUF_PUSH_3(start_memory, regnum, 0);
1512 }
1513 compile_stack.avail++;
1514
1515 fixup_alt_jump = 0;
1516 laststart = 0;
1517 begalt = b;
090089c4 1518 /* If we've reached MAX_REGNUM groups, then this open
b8d8561b 1519 * won't actually generate any code, so we'll have to
1520 * clear pending_exact explicitly. */
090089c4 1521 pending_exact = 0;
b8d8561b 1522 break;
1523
1524
1525 case ')':
1526 if (syntax & RE_NO_BK_PARENS)
1527 goto normal_backslash;
1528
a3f9588e 1529 if (COMPILE_STACK_EMPTY) {
b8d8561b 1530 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
1531 goto normal_backslash;
1532 else
1533 return REG_ERPAREN;
a3f9588e 1534 }
b8d8561b 1535 handle_close:
1536 if (fixup_alt_jump) { /* Push a dummy failure point at the end of the
1537 * alternative for a possible future
1538 * `pop_failure_jump' to pop. See comments at
1539 * `push_dummy_failure' in `re_match_2'. */
1540 BUF_PUSH(push_dummy_failure);
1541
1542 /* We allocated space for this jump when we assigned
1543 * to `fixup_alt_jump', in the `handle_alt' case below. */
1544 STORE_JUMP(jump_past_alt, fixup_alt_jump, b - 1);
1545 }
1546 /* See similar code for backslashed left paren above. */
a3f9588e 1547 if (COMPILE_STACK_EMPTY) {
b8d8561b 1548 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
1549 goto normal_char;
1550 else
1551 return REG_ERPAREN;
a3f9588e 1552 }
b8d8561b 1553 /* Since we just checked for an empty stack above, this
1554 * ``can't happen''. */
1555 assert(compile_stack.avail != 0);
1556 {
1557 /* We don't just want to restore into `regnum', because
1558 * later groups should continue to be numbered higher,
1559 * as in `(ab)c(de)' -- the second group is #2. */
1560 regnum_t this_group_regnum;
1561
1562 compile_stack.avail--;
1563 begalt = bufp->buffer + COMPILE_STACK_TOP.begalt_offset;
1564 fixup_alt_jump
1565 = COMPILE_STACK_TOP.fixup_alt_jump
1566 ? bufp->buffer + COMPILE_STACK_TOP.fixup_alt_jump - 1
1567 : 0;
1568 laststart = bufp->buffer + COMPILE_STACK_TOP.laststart_offset;
1569 this_group_regnum = COMPILE_STACK_TOP.regnum;
1570 /* If we've reached MAX_REGNUM groups, then this open
1571 * won't actually generate any code, so we'll have to
1572 * clear pending_exact explicitly. */
1573 pending_exact = 0;
1574
1575 /* We're at the end of the group, so now we know how many
1576 * groups were inside this one. */
1577 if (this_group_regnum <= MAX_REGNUM) {
1578 unsigned char *inner_group_loc
1579 = bufp->buffer + COMPILE_STACK_TOP.inner_group_offset;
1580
1581 *inner_group_loc = regnum - this_group_regnum;
1582 BUF_PUSH_3(stop_memory, this_group_regnum,
1583 regnum - this_group_regnum);
1584 }
1585 }
1586 break;
1587
1588
1589 case '|': /* `\|'. */
1590 if (syntax & RE_LIMITED_OPS || syntax & RE_NO_BK_VBAR)
1591 goto normal_backslash;
1592 handle_alt:
1593 if (syntax & RE_LIMITED_OPS)
1594 goto normal_char;
1595
1596 /* Insert before the previous alternative a jump which
1597 * jumps to this alternative if the former fails. */
1598 GET_BUFFER_SPACE(3);
1599 INSERT_JUMP(on_failure_jump, begalt, b + 6);
1600 pending_exact = 0;
1601 b += 3;
1602
1603 /* The alternative before this one has a jump after it
1604 * which gets executed if it gets matched. Adjust that
1605 * jump so it will jump to this alternative's analogous
1606 * jump (put in below, which in turn will jump to the next
1607 * (if any) alternative's such jump, etc.). The last such
1608 * jump jumps to the correct final destination. A picture:
1609 * _____ _____
1610 * | | | |
1611 * | v | v
1612 * a | b | c
1613 *
1614 * If we are at `b', then fixup_alt_jump right now points to a
1615 * three-byte space after `a'. We'll put in the jump, set
1616 * fixup_alt_jump to right after `b', and leave behind three
1617 * bytes which we'll fill in when we get to after `c'. */
1618
1619 if (fixup_alt_jump)
1620 STORE_JUMP(jump_past_alt, fixup_alt_jump, b);
1621
1622 /* Mark and leave space for a jump after this alternative,
1623 * to be filled in later either by next alternative or
1624 * when know we're at the end of a series of alternatives. */
1625 fixup_alt_jump = b;
1626 GET_BUFFER_SPACE(3);
1627 b += 3;
1628
1629 laststart = 0;
1630 begalt = b;
1631 break;
1632
1633
1634 case '{':
1635 /* If \{ is a literal. */
1636 if (!(syntax & RE_INTERVALS)
1637 /* If we're at `\{' and it's not the open-interval
1638 * operator. */
1639 || ((syntax & RE_INTERVALS) && (syntax & RE_NO_BK_BRACES))
1640 || (p - 2 == pattern && p == pend))
1641 goto normal_backslash;
1642
1643 handle_interval:
1644 {
1645 /* If got here, then the syntax allows intervals. */
1646
1647 /* At least (most) this many matches must be made. */
1648 int lower_bound = -1, upper_bound = -1;
1649
1650 beg_interval = p - 1;
1651
1652 if (p == pend) {
1653 if (syntax & RE_NO_BK_BRACES)
1654 goto unfetch_interval;
1655 else
1656 return REG_EBRACE;
1657 }
1658 GET_UNSIGNED_NUMBER(lower_bound);
1659
1660 if (c == ',') {
1661 GET_UNSIGNED_NUMBER(upper_bound);
1662 if (upper_bound < 0)
1663 upper_bound = RE_DUP_MAX;
1664 } else
1665 /* Interval such as `{1}' => match exactly once. */
1666 upper_bound = lower_bound;
1667
1668 if (lower_bound < 0 || upper_bound > RE_DUP_MAX
1669 || lower_bound > upper_bound) {
1670 if (syntax & RE_NO_BK_BRACES)
1671 goto unfetch_interval;
1672 else
1673 return REG_BADBR;
1674 }
1675 if (!(syntax & RE_NO_BK_BRACES)) {
1676 if (c != '\\')
1677 return REG_EBRACE;
1678
1679 PATFETCH(c);
1680 }
1681 if (c != '}') {
1682 if (syntax & RE_NO_BK_BRACES)
1683 goto unfetch_interval;
1684 else
1685 return REG_BADBR;
1686 }
1687 /* We just parsed a valid interval. */
1688
1689 /* If it's invalid to have no preceding re. */
1690 if (!laststart) {
1691 if (syntax & RE_CONTEXT_INVALID_OPS)
1692 return REG_BADRPT;
1693 else if (syntax & RE_CONTEXT_INDEP_OPS)
1694 laststart = b;
1695 else
1696 goto unfetch_interval;
1697 }
1698 /* If the upper bound is zero, don't want to succeed at
1699 * all; jump from `laststart' to `b + 3', which will be
1700 * the end of the buffer after we insert the jump. */
1701 if (upper_bound == 0) {
1702 GET_BUFFER_SPACE(3);
1703 INSERT_JUMP(jump, laststart, b + 3);
1704 b += 3;
1705 }
1706 /* Otherwise, we have a nontrivial interval. When
1707 * we're all done, the pattern will look like:
1708 * set_number_at <jump count> <upper bound>
1709 * set_number_at <succeed_n count> <lower bound>
1710 * succeed_n <after jump addr> <succed_n count>
1711 * <body of loop>
1712 * jump_n <succeed_n addr> <jump count>
1713 * (The upper bound and `jump_n' are omitted if
1714 * `upper_bound' is 1, though.) */
1715 else { /* If the upper bound is > 1, we need to insert
1716 * more at the end of the loop. */
1717 unsigned nbytes = 10 + (upper_bound > 1) * 10;
1718
1719 GET_BUFFER_SPACE(nbytes);
1720
1721 /* Initialize lower bound of the `succeed_n', even
1722 * though it will be set during matching by its
1723 * attendant `set_number_at' (inserted next),
1724 * because `re_compile_fastmap' needs to know.
1725 * Jump to the `jump_n' we might insert below. */
1726 INSERT_JUMP2(succeed_n, laststart,
1727 b + 5 + (upper_bound > 1) * 5,
1728 lower_bound);
1729 b += 5;
1730
1731 /* Code to initialize the lower bound. Insert
1732 * before the `succeed_n'. The `5' is the last two
1733 * bytes of this `set_number_at', plus 3 bytes of
1734 * the following `succeed_n'. */
1735 insert_op2(set_number_at, laststart, 5, lower_bound, b);
1736 b += 5;
1737
1738 if (upper_bound > 1) { /* More than one repetition is allowed, so
1739 * append a backward jump to the `succeed_n'
1740 * that starts this interval.
1741 *
1742 * When we've reached this during matching,
1743 * we'll have matched the interval once, so
1744 * jump back only `upper_bound - 1' times. */
1745 STORE_JUMP2(jump_n, b, laststart + 5,
1746 upper_bound - 1);
1747 b += 5;
1748
1749 /* The location we want to set is the second
1750 * parameter of the `jump_n'; that is `b-2' as
1751 * an absolute address. `laststart' will be
1752 * the `set_number_at' we're about to insert;
1753 * `laststart+3' the number to set, the source
1754 * for the relative address. But we are
1755 * inserting into the middle of the pattern --
1756 * so everything is getting moved up by 5.
1757 * Conclusion: (b - 2) - (laststart + 3) + 5,
1758 * i.e., b - laststart.
1759 *
1760 * We insert this at the beginning of the loop
1761 * so that if we fail during matching, we'll
1762 * reinitialize the bounds. */
1763 insert_op2(set_number_at, laststart, b - laststart,
1764 upper_bound - 1, b);
1765 b += 5;
1766 }
1767 }
1768 pending_exact = 0;
1769 beg_interval = NULL;
1770 }
1771 break;
1772
1773 unfetch_interval:
1774 /* If an invalid interval, match the characters as literals. */
1775 assert(beg_interval);
1776 p = beg_interval;
1777 beg_interval = NULL;
090089c4 1778
b8d8561b 1779 /* normal_char and normal_backslash need `c'. */
1780 PATFETCH(c);
1781
1782 if (!(syntax & RE_NO_BK_BRACES)) {
1783 if (p > pattern && p[-1] == '\\')
1784 goto normal_backslash;
1785 }
1786 goto normal_char;
090089c4 1787
090089c4 1788
b8d8561b 1789 case 'w':
1790 laststart = b;
1791 BUF_PUSH(wordchar);
1792 break;
090089c4 1793
1794
b8d8561b 1795 case 'W':
1796 laststart = b;
1797 BUF_PUSH(notwordchar);
1798 break;
090089c4 1799
1800
b8d8561b 1801 case '<':
1802 BUF_PUSH(wordbeg);
1803 break;
090089c4 1804
b8d8561b 1805 case '>':
1806 BUF_PUSH(wordend);
1807 break;
090089c4 1808
b8d8561b 1809 case 'b':
1810 BUF_PUSH(wordbound);
1811 break;
090089c4 1812
b8d8561b 1813 case 'B':
1814 BUF_PUSH(notwordbound);
1815 break;
090089c4 1816
b8d8561b 1817 case '`':
1818 BUF_PUSH(begbuf);
1819 break;
090089c4 1820
b8d8561b 1821 case '\'':
1822 BUF_PUSH(endbuf);
1823 break;
090089c4 1824
b8d8561b 1825 case '1':
1826 case '2':
1827 case '3':
1828 case '4':
1829 case '5':
1830 case '6':
1831 case '7':
1832 case '8':
1833 case '9':
1834 if (syntax & RE_NO_BK_REFS)
1835 goto normal_char;
090089c4 1836
b8d8561b 1837 c1 = c - '0';
090089c4 1838
b8d8561b 1839 if (c1 > regnum)
1840 return REG_ESUBREG;
090089c4 1841
b8d8561b 1842 /* Can't back reference to a subexpression if inside of it. */
1843 if (group_in_compile_stack(compile_stack, c1))
1844 goto normal_char;
090089c4 1845
b8d8561b 1846 laststart = b;
1847 BUF_PUSH_2(duplicate, c1);
1848 break;
090089c4 1849
1850
b8d8561b 1851 case '+':
1852 case '?':
1853 if (syntax & RE_BK_PLUS_QM)
1854 goto handle_plus;
1855 else
1856 goto normal_backslash;
090089c4 1857
b8d8561b 1858 default:
1859 normal_backslash:
1860 /* You might think it would be useful for \ to mean
1861 * not to translate; but if we don't translate it
1862 * it will never match anything. */
1863 c = TRANSLATE(c);
1864 goto normal_char;
1865 }
1866 break;
090089c4 1867
1868
1869 default:
b8d8561b 1870 /* Expects the character in `c'. */
1871 normal_char:
1872 /* If no exactn currently being built. */
1873 if (!pending_exact
1874
1875 /* If last exactn not at current position. */
1876 || pending_exact + *pending_exact + 1 != b
1877
1878 /* We have only one byte following the exactn for the count. */
1879 || *pending_exact == (1 << BYTEWIDTH) - 1
1880
1881 /* If followed by a repetition operator. */
1882 || *p == '*' || *p == '^'
1883 || ((syntax & RE_BK_PLUS_QM)
1884 ? *p == '\\' && (p[1] == '+' || p[1] == '?')
1885 : (*p == '+' || *p == '?'))
1886 || ((syntax & RE_INTERVALS)
1887 && ((syntax & RE_NO_BK_BRACES)
1888 ? *p == '{'
1889 : (p[0] == '\\' && p[1] == '{')))) {
1890 /* Start building a new exactn. */
1891
1892 laststart = b;
1893
1894 BUF_PUSH_2(exactn, 0);
1895 pending_exact = b - 1;
1896 }
1897 BUF_PUSH(c);
1898 (*pending_exact)++;
1899 break;
1900 } /* switch (c) */
1901 } /* while p != pend */
1902
1903
1904 /* Through the pattern now. */
1905
1906 if (fixup_alt_jump)
1907 STORE_JUMP(jump_past_alt, fixup_alt_jump, b);
1908
1909 if (!COMPILE_STACK_EMPTY)
1910 return REG_EPAREN;
1911
1912 free(compile_stack.stack);
1913
1914 /* We have succeeded; set the length of the buffer. */
1915 bufp->used = b - bufp->buffer;
090089c4 1916
1917#ifdef DEBUG
b8d8561b 1918 if (debug) {
1919 DEBUG_PRINT1("\nCompiled pattern: ");
1920 print_compiled_pattern(bufp);
090089c4 1921 }
1922#endif /* DEBUG */
1923
b8d8561b 1924 return REG_NOERROR;
1925} /* regex_compile */
090089c4 1926\f
1927/* Subroutines for `regex_compile'. */
1928
1929/* Store OP at LOC followed by two-byte integer parameter ARG. */
1930
08bc07d0 1931void store_op1(re_opcode_t op, unsigned char *loc, int arg)
090089c4 1932{
b8d8561b 1933 *loc = (unsigned char) op;
1934 STORE_NUMBER(loc + 1, arg);
090089c4 1935}
1936
1937
1938/* Like `store_op1', but for two two-byte parameters ARG1 and ARG2. */
1939
08bc07d0 1940void
1941store_op2( re_opcode_t op, unsigned char *loc, int arg1, int arg2)
090089c4 1942{
b8d8561b 1943 *loc = (unsigned char) op;
1944 STORE_NUMBER(loc + 1, arg1);
1945 STORE_NUMBER(loc + 3, arg2);
090089c4 1946}
1947
1948
1949/* Copy the bytes from LOC to END to open up three bytes of space at LOC
b8d8561b 1950 * for OP followed by two-byte integer parameter ARG. */
090089c4 1951
08bc07d0 1952void
1953insert_op1(re_opcode_t op, unsigned char *loc, int arg, unsigned char *end)
090089c4 1954{
b8d8561b 1955 register unsigned char *pfrom = end;
1956 register unsigned char *pto = end + 3;
1957
1958 while (pfrom != loc)
1959 *--pto = *--pfrom;
090089c4 1960
b8d8561b 1961 store_op1(op, loc, arg);
090089c4 1962}
1963
1964
1965/* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2. */
1966
08bc07d0 1967void
1968insert_op2(re_opcode_t op, unsigned char *loc, int arg1, int arg2, unsigned char *end)
090089c4 1969{
b8d8561b 1970 register unsigned char *pfrom = end;
1971 register unsigned char *pto = end + 5;
090089c4 1972
b8d8561b 1973 while (pfrom != loc)
1974 *--pto = *--pfrom;
1975
1976 store_op2(op, loc, arg1, arg2);
090089c4 1977}
1978
1979
1980/* P points to just after a ^ in PATTERN. Return true if that ^ comes
b8d8561b 1981 * after an alternative or a begin-subexpression. We assume there is at
1982 * least one character before the ^. */
090089c4 1983
08bc07d0 1984boolean
1985at_begline_loc_p(const char * pattern, const char *p, reg_syntax_t syntax)
090089c4 1986{
b8d8561b 1987 const char *prev = p - 2;
1988 boolean prev_prev_backslash = prev > pattern && prev[-1] == '\\';
1989
1990 return
1991 /* After a subexpression? */
1992 (*prev == '(' && (syntax & RE_NO_BK_PARENS || prev_prev_backslash))
1993 /* After an alternative? */
1994 || (*prev == '|' && (syntax & RE_NO_BK_VBAR || prev_prev_backslash));
090089c4 1995}
1996
1997
1998/* The dual of at_begline_loc_p. This one is for $. We assume there is
b8d8561b 1999 * at least one character after the $, i.e., `P < PEND'. */
090089c4 2000
08bc07d0 2001boolean
2002at_endline_loc_p(const char *p, const char *pend, int syntax)
090089c4 2003{
b8d8561b 2004 const char *next = p;
2005 boolean next_backslash = *next == '\\';
2006 const char *next_next = p + 1 < pend ? p + 1 : NULL;
2007
2008 return
2009 /* Before a subexpression? */
2010 (syntax & RE_NO_BK_PARENS ? *next == ')'
2011 : next_backslash && next_next && *next_next == ')')
2012 /* Before an alternative? */
2013 || (syntax & RE_NO_BK_VBAR ? *next == '|'
2014 : next_backslash && next_next && *next_next == '|');
090089c4 2015}
2016
2017
2018/* Returns true if REGNUM is in one of COMPILE_STACK's elements and
b8d8561b 2019 * false if it's not. */
090089c4 2020
08bc07d0 2021boolean
2022group_in_compile_stack(compile_stack_type compile_stack, regnum_t regnum)
090089c4 2023{
b8d8561b 2024 int this_element;
090089c4 2025
b8d8561b 2026 for (this_element = compile_stack.avail - 1;
2027 this_element >= 0;
2028 this_element--)
2029 if (compile_stack.stack[this_element].regnum == regnum)
2030 return true;
090089c4 2031
b8d8561b 2032 return false;
090089c4 2033}
2034
2035
2036/* Read the ending character of a range (in a bracket expression) from the
b8d8561b 2037 * uncompiled pattern *P_PTR (which ends at PEND). We assume the
2038 * starting character is in `P[-2]'. (`P[-1]' is the character `-'.)
2039 * Then we set the translation of all bits between the starting and
2040 * ending characters (inclusive) in the compiled pattern B.
2041 *
2042 * Return an error code.
2043 *
2044 * We use these short variable names so we can use the same macros as
2045 * `regex_compile' itself. */
090089c4 2046
08bc07d0 2047reg_errcode_t
2048compile_range(const char **p_ptr, const char *pend, char *translate, reg_syntax_t syntax, unsigned char *b)
090089c4 2049{
b8d8561b 2050 unsigned this_char;
2051
2052 const char *p = *p_ptr;
2053 int range_start, range_end;
2054
2055 if (p == pend)
2056 return REG_ERANGE;
2057
2058 /* Even though the pattern is a signed `char *', we need to fetch
2059 * with unsigned char *'s; if the high bit of the pattern character
2060 * is set, the range endpoints will be negative if we fetch using a
2061 * signed char *.
2062 *
2063 * We also want to fetch the endpoints without translating them; the
2064 * appropriate translation is done in the bit-setting loop below. */
2065 range_start = ((unsigned char *) p)[-2];
2066 range_end = ((unsigned char *) p)[0];
2067
2068 /* Have to increment the pointer into the pattern string, so the
2069 * caller isn't still at the ending character. */
2070 (*p_ptr)++;
2071
2072 /* If the start is after the end, the range is empty. */
2073 if (range_start > range_end)
2074 return syntax & RE_NO_EMPTY_RANGES ? REG_ERANGE : REG_NOERROR;
2075
2076 /* Here we see why `this_char' has to be larger than an `unsigned
2077 * char' -- the range is inclusive, so if `range_end' == 0xff
2078 * (assuming 8-bit characters), we would otherwise go into an infinite
2079 * loop, since all characters <= 0xff. */
2080 for (this_char = range_start; this_char <= range_end; this_char++) {
2081 SET_LIST_BIT(TRANSLATE(this_char));
090089c4 2082 }
b8d8561b 2083
2084 return REG_NOERROR;
090089c4 2085}
2086\f
2087/* Failure stack declarations and macros; both re_compile_fastmap and
b8d8561b 2088 * re_match_2 use a failure stack. These have to be macros because of
2089 * REGEX_ALLOCATE. */
2090
090089c4 2091
2092/* Number of failure points for which to initially allocate space
b8d8561b 2093 * when matching. If this number is exceeded, we allocate more
2094 * space, so it is not a hard limit. */
090089c4 2095#ifndef INIT_FAILURE_ALLOC
2096#define INIT_FAILURE_ALLOC 5
2097#endif
2098
2099/* Roughly the maximum number of failure points on the stack. Would be
b8d8561b 2100 * exactly that if always used MAX_FAILURE_SPACE each time we failed.
2101 * This is a variable only so users of regex can assign to it; we never
2102 * change it ourselves. */
090089c4 2103int re_max_failures = 2000;
2104
2105typedef const unsigned char *fail_stack_elt_t;
2106
b8d8561b 2107typedef struct {
2108 fail_stack_elt_t *stack;
2109 unsigned size;
2110 unsigned avail; /* Offset of next open position. */
090089c4 2111} fail_stack_type;
2112
2113#define FAIL_STACK_EMPTY() (fail_stack.avail == 0)
2114#define FAIL_STACK_PTR_EMPTY() (fail_stack_ptr->avail == 0)
2115#define FAIL_STACK_FULL() (fail_stack.avail == fail_stack.size)
2116#define FAIL_STACK_TOP() (fail_stack.stack[fail_stack.avail])
2117
2118
2119/* Initialize `fail_stack'. Do `return -2' if the alloc fails. */
2120
2121#define INIT_FAIL_STACK() \
2122 do { \
2123 fail_stack.stack = (fail_stack_elt_t *) \
2124 REGEX_ALLOCATE (INIT_FAILURE_ALLOC * sizeof (fail_stack_elt_t)); \
2125 \
2126 if (fail_stack.stack == NULL) \
2127 return -2; \
2128 \
2129 fail_stack.size = INIT_FAILURE_ALLOC; \
2130 fail_stack.avail = 0; \
2131 } while (0)
2132
2133
2134/* Double the size of FAIL_STACK, up to approximately `re_max_failures' items.
b8d8561b 2135 *
2136 * Return 1 if succeeds, and 0 if either ran out of memory
2137 * allocating space for it or it was already too large.
2138 *
2139 * REGEX_REALLOCATE requires `destination' be declared. */
090089c4 2140
2141#define DOUBLE_FAIL_STACK(fail_stack) \
2142 ((fail_stack).size > re_max_failures * MAX_FAILURE_ITEMS \
2143 ? 0 \
2144 : ((fail_stack).stack = (fail_stack_elt_t *) \
2145 REGEX_REALLOCATE ((fail_stack).stack, \
2146 (fail_stack).size * sizeof (fail_stack_elt_t), \
2147 ((fail_stack).size << 1) * sizeof (fail_stack_elt_t)), \
2148 \
2149 (fail_stack).stack == NULL \
2150 ? 0 \
2151 : ((fail_stack).size <<= 1, \
2152 1)))
2153
2154
2155/* Push PATTERN_OP on FAIL_STACK.
b8d8561b 2156 *
2157 * Return 1 if was able to do so and 0 if ran out of memory allocating
2158 * space to do so. */
090089c4 2159#define PUSH_PATTERN_OP(pattern_op, fail_stack) \
2160 ((FAIL_STACK_FULL () \
2161 && !DOUBLE_FAIL_STACK (fail_stack)) \
2162 ? 0 \
2163 : ((fail_stack).stack[(fail_stack).avail++] = pattern_op, \
2164 1))
2165
2166/* This pushes an item onto the failure stack. Must be a four-byte
b8d8561b 2167 * value. Assumes the variable `fail_stack'. Probably should only
2168 * be called from within `PUSH_FAILURE_POINT'. */
090089c4 2169#define PUSH_FAILURE_ITEM(item) \
2170 fail_stack.stack[fail_stack.avail++] = (fail_stack_elt_t) item
2171
2172/* The complement operation. Assumes `fail_stack' is nonempty. */
2173#define POP_FAILURE_ITEM() fail_stack.stack[--fail_stack.avail]
2174
2175/* Used to omit pushing failure point id's when we're not debugging. */
2176#ifdef DEBUG
2177#define DEBUG_PUSH PUSH_FAILURE_ITEM
2178#define DEBUG_POP(item_addr) *(item_addr) = POP_FAILURE_ITEM ()
2179#else
2180#define DEBUG_PUSH(item)
2181#define DEBUG_POP(item_addr)
2182#endif
2183
2184
2185/* Push the information about the state we will need
b8d8561b 2186 * if we ever fail back to it.
2187 *
2188 * Requires variables fail_stack, regstart, regend, reg_info, and
2189 * num_regs be declared. DOUBLE_FAIL_STACK requires `destination' be
2190 * declared.
2191 *
2192 * Does `return FAILURE_CODE' if runs out of memory. */
090089c4 2193
2194#define PUSH_FAILURE_POINT(pattern_place, string_place, failure_code) \
2195 do { \
2196 char *destination; \
2197 /* Must be int, so when we don't save any registers, the arithmetic \
2198 of 0 + -1 isn't done as unsigned. */ \
2199 int this_reg; \
2200 \
2201 DEBUG_STATEMENT (failure_id++); \
2202 DEBUG_STATEMENT (nfailure_points_pushed++); \
2203 DEBUG_PRINT2 ("\nPUSH_FAILURE_POINT #%u:\n", failure_id); \
2204 DEBUG_PRINT2 (" Before push, next avail: %d\n", (fail_stack).avail);\
2205 DEBUG_PRINT2 (" size: %d\n", (fail_stack).size);\
2206 \
2207 DEBUG_PRINT2 (" slots needed: %d\n", NUM_FAILURE_ITEMS); \
2208 DEBUG_PRINT2 (" available: %d\n", REMAINING_AVAIL_SLOTS); \
2209 \
2210 /* Ensure we have enough space allocated for what we will push. */ \
2211 while (REMAINING_AVAIL_SLOTS < NUM_FAILURE_ITEMS) \
2212 { \
2213 if (!DOUBLE_FAIL_STACK (fail_stack)) \
2214 return failure_code; \
2215 \
2216 DEBUG_PRINT2 ("\n Doubled stack; size now: %d\n", \
2217 (fail_stack).size); \
2218 DEBUG_PRINT2 (" slots available: %d\n", REMAINING_AVAIL_SLOTS);\
2219 } \
2220 \
2221 /* Push the info, starting with the registers. */ \
2222 DEBUG_PRINT1 ("\n"); \
2223 \
2224 for (this_reg = lowest_active_reg; this_reg <= highest_active_reg; \
2225 this_reg++) \
2226 { \
2227 DEBUG_PRINT2 (" Pushing reg: %d\n", this_reg); \
2228 DEBUG_STATEMENT (num_regs_pushed++); \
2229 \
2230 DEBUG_PRINT2 (" start: 0x%x\n", regstart[this_reg]); \
2231 PUSH_FAILURE_ITEM (regstart[this_reg]); \
2232 \
2233 DEBUG_PRINT2 (" end: 0x%x\n", regend[this_reg]); \
2234 PUSH_FAILURE_ITEM (regend[this_reg]); \
2235 \
2236 DEBUG_PRINT2 (" info: 0x%x\n ", reg_info[this_reg]); \
2237 DEBUG_PRINT2 (" match_null=%d", \
2238 REG_MATCH_NULL_STRING_P (reg_info[this_reg])); \
2239 DEBUG_PRINT2 (" active=%d", IS_ACTIVE (reg_info[this_reg])); \
2240 DEBUG_PRINT2 (" matched_something=%d", \
2241 MATCHED_SOMETHING (reg_info[this_reg])); \
2242 DEBUG_PRINT2 (" ever_matched=%d", \
2243 EVER_MATCHED_SOMETHING (reg_info[this_reg])); \
2244 DEBUG_PRINT1 ("\n"); \
2245 PUSH_FAILURE_ITEM (reg_info[this_reg].word); \
2246 } \
2247 \
2248 DEBUG_PRINT2 (" Pushing low active reg: %d\n", lowest_active_reg);\
2249 PUSH_FAILURE_ITEM (lowest_active_reg); \
2250 \
2251 DEBUG_PRINT2 (" Pushing high active reg: %d\n", highest_active_reg);\
2252 PUSH_FAILURE_ITEM (highest_active_reg); \
2253 \
2254 DEBUG_PRINT2 (" Pushing pattern 0x%x: ", pattern_place); \
2255 DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern_place, pend); \
2256 PUSH_FAILURE_ITEM (pattern_place); \
2257 \
2258 DEBUG_PRINT2 (" Pushing string 0x%x: `", string_place); \
2259 DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2, \
2260 size2); \
2261 DEBUG_PRINT1 ("'\n"); \
2262 PUSH_FAILURE_ITEM (string_place); \
2263 \
2264 DEBUG_PRINT2 (" Pushing failure id: %u\n", failure_id); \
2265 DEBUG_PUSH (failure_id); \
2266 } while (0)
2267
2268/* This is the number of items that are pushed and popped on the stack
b8d8561b 2269 * for each register. */
090089c4 2270#define NUM_REG_ITEMS 3
2271
2272/* Individual items aside from the registers. */
2273#ifdef DEBUG
b8d8561b 2274#define NUM_NONREG_ITEMS 5 /* Includes failure point id. */
090089c4 2275#else
2276#define NUM_NONREG_ITEMS 4
2277#endif
2278
2279/* We push at most this many items on the stack. */
2280#define MAX_FAILURE_ITEMS ((num_regs - 1) * NUM_REG_ITEMS + NUM_NONREG_ITEMS)
2281
2282/* We actually push this many items. */
2283#define NUM_FAILURE_ITEMS \
2284 ((highest_active_reg - lowest_active_reg + 1) * NUM_REG_ITEMS \
2285 + NUM_NONREG_ITEMS)
2286
2287/* How many items can still be added to the stack without overflowing it. */
2288#define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)
2289
2290
2291/* Pops what PUSH_FAIL_STACK pushes.
b8d8561b 2292 *
2293 * We restore into the parameters, all of which should be lvalues:
2294 * STR -- the saved data position.
2295 * PAT -- the saved pattern position.
2296 * LOW_REG, HIGH_REG -- the highest and lowest active registers.
2297 * REGSTART, REGEND -- arrays of string positions.
2298 * REG_INFO -- array of information about each subexpression.
2299 *
2300 * Also assumes the variables `fail_stack' and (if debugging), `bufp',
2301 * `pend', `string1', `size1', `string2', and `size2'. */
090089c4 2302
2303#define POP_FAILURE_POINT(str, pat, low_reg, high_reg, regstart, regend, reg_info)\
2304{ \
2305 DEBUG_STATEMENT (fail_stack_elt_t failure_id;) \
2306 int this_reg; \
2307 const unsigned char *string_temp; \
2308 \
2309 assert (!FAIL_STACK_EMPTY ()); \
2310 \
2311 /* Remove failure points and point to how many regs pushed. */ \
2312 DEBUG_PRINT1 ("POP_FAILURE_POINT:\n"); \
2313 DEBUG_PRINT2 (" Before pop, next avail: %d\n", fail_stack.avail); \
2314 DEBUG_PRINT2 (" size: %d\n", fail_stack.size); \
2315 \
2316 assert (fail_stack.avail >= NUM_NONREG_ITEMS); \
2317 \
2318 DEBUG_POP (&failure_id); \
2319 DEBUG_PRINT2 (" Popping failure id: %u\n", failure_id); \
2320 \
2321 /* If the saved string location is NULL, it came from an \
2322 on_failure_keep_string_jump opcode, and we want to throw away the \
2323 saved NULL, thus retaining our current position in the string. */ \
2324 string_temp = POP_FAILURE_ITEM (); \
2325 if (string_temp != NULL) \
2326 str = (const char *) string_temp; \
2327 \
2328 DEBUG_PRINT2 (" Popping string 0x%x: `", str); \
2329 DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2); \
2330 DEBUG_PRINT1 ("'\n"); \
2331 \
2332 pat = (unsigned char *) POP_FAILURE_ITEM (); \
2333 DEBUG_PRINT2 (" Popping pattern 0x%x: ", pat); \
2334 DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend); \
2335 \
2336 /* Restore register info. */ \
30a4f2a8 2337 high_reg = (unsigned long) POP_FAILURE_ITEM (); \
090089c4 2338 DEBUG_PRINT2 (" Popping high active reg: %d\n", high_reg); \
2339 \
30a4f2a8 2340 low_reg = (unsigned long) POP_FAILURE_ITEM (); \
090089c4 2341 DEBUG_PRINT2 (" Popping low active reg: %d\n", low_reg); \
2342 \
2343 for (this_reg = high_reg; this_reg >= low_reg; this_reg--) \
2344 { \
2345 DEBUG_PRINT2 (" Popping reg: %d\n", this_reg); \
2346 \
2347 reg_info[this_reg].word = POP_FAILURE_ITEM (); \
2348 DEBUG_PRINT2 (" info: 0x%x\n", reg_info[this_reg]); \
2349 \
2350 regend[this_reg] = (const char *) POP_FAILURE_ITEM (); \
2351 DEBUG_PRINT2 (" end: 0x%x\n", regend[this_reg]); \
2352 \
2353 regstart[this_reg] = (const char *) POP_FAILURE_ITEM (); \
2354 DEBUG_PRINT2 (" start: 0x%x\n", regstart[this_reg]); \
2355 } \
2356 \
2357 DEBUG_STATEMENT (nfailure_points_popped++); \
b8d8561b 2358} /* POP_FAILURE_POINT */
090089c4 2359\f
2360/* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
b8d8561b 2361 * BUFP. A fastmap records which of the (1 << BYTEWIDTH) possible
2362 * characters can start a string that matches the pattern. This fastmap
2363 * is used by re_search to skip quickly over impossible starting points.
2364 *
2365 * The caller must supply the address of a (1 << BYTEWIDTH)-byte data
2366 * area as BUFP->fastmap.
2367 *
2368 * We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
2369 * the pattern buffer.
2370 *
2371 * Returns 0 if we succeed, -2 if an internal error. */
090089c4 2372
2373int
b8d8561b 2374re_compile_fastmap(bufp)
090089c4 2375 struct re_pattern_buffer *bufp;
2376{
b8d8561b 2377 int j, k;
2378 fail_stack_type fail_stack;
090089c4 2379#ifndef REGEX_MALLOC
b8d8561b 2380 char *destination;
090089c4 2381#endif
b8d8561b 2382 /* We don't push any register information onto the failure stack. */
2383 unsigned num_regs = 0;
2384
2385 register char *fastmap = bufp->fastmap;
2386 unsigned char *pattern = bufp->buffer;
2387 unsigned long size = bufp->used;
2388 const unsigned char *p = pattern;
2389 register unsigned char *pend = pattern + size;
2390
2391 /* Assume that each path through the pattern can be null until
2392 * proven otherwise. We set this false at the bottom of switch
2393 * statement, to which we get only if a particular path doesn't
2394 * match the empty string. */
2395 boolean path_can_be_null = true;
2396
2397 /* We aren't doing a `succeed_n' to begin with. */
2398 boolean succeed_n_p = false;
2399
2400 assert(fastmap != NULL && p != NULL);
2401
2402 INIT_FAIL_STACK();
0e473d70 2403 memset(fastmap, 0, 1 << BYTEWIDTH); /* Assume nothing's valid. */
b8d8561b 2404 bufp->fastmap_accurate = 1; /* It will be when we're done. */
2405 bufp->can_be_null = 0;
2406
2407 while (p != pend || !FAIL_STACK_EMPTY()) {
2408 if (p == pend) {
2409 bufp->can_be_null |= path_can_be_null;
2410
2411 /* Reset for next path. */
2412 path_can_be_null = true;
2413
2414 p = fail_stack.stack[--fail_stack.avail];
090089c4 2415 }
b8d8561b 2416 /* We should never be about to go beyond the end of the pattern. */
2417 assert(p < pend);
090089c4 2418
090089c4 2419#ifdef SWITCH_ENUM_BUG
b8d8561b 2420 switch ((int) ((re_opcode_t) * p++))
090089c4 2421#else
b8d8561b 2422 switch ((re_opcode_t) * p++)
090089c4 2423#endif
2424 {
2425
b8d8561b 2426 /* I guess the idea here is to simply not bother with a fastmap
2427 * if a backreference is used, since it's too hard to figure out
2428 * the fastmap for the corresponding group. Setting
2429 * `can_be_null' stops `re_search_2' from using the fastmap, so
2430 * that is all we do. */
090089c4 2431 case duplicate:
b8d8561b 2432 bufp->can_be_null = 1;
2433 return 0;
090089c4 2434
2435
b8d8561b 2436 /* Following are the cases which match a character. These end
2437 * with `break'. */
090089c4 2438
2439 case exactn:
b8d8561b 2440 fastmap[p[1]] = 1;
2441 break;
090089c4 2442
2443
b8d8561b 2444 case charset:
2445 for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
2446 if (p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH)))
2447 fastmap[j] = 1;
2448 break;
090089c4 2449
2450
2451 case charset_not:
b8d8561b 2452 /* Chars beyond end of map must be allowed. */
2453 for (j = *p * BYTEWIDTH; j < (1 << BYTEWIDTH); j++)
2454 fastmap[j] = 1;
090089c4 2455
b8d8561b 2456 for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
2457 if (!(p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH))))
2458 fastmap[j] = 1;
2459 break;
090089c4 2460
2461
2462 case wordchar:
b8d8561b 2463 for (j = 0; j < (1 << BYTEWIDTH); j++)
2464 if (SYNTAX(j) == Sword)
2465 fastmap[j] = 1;
2466 break;
090089c4 2467
2468
2469 case notwordchar:
b8d8561b 2470 for (j = 0; j < (1 << BYTEWIDTH); j++)
2471 if (SYNTAX(j) != Sword)
2472 fastmap[j] = 1;
2473 break;
090089c4 2474
2475
b8d8561b 2476 case anychar:
2477 /* `.' matches anything ... */
2478 for (j = 0; j < (1 << BYTEWIDTH); j++)
2479 fastmap[j] = 1;
090089c4 2480
b8d8561b 2481 /* ... except perhaps newline. */
2482 if (!(bufp->syntax & RE_DOT_NEWLINE))
2483 fastmap['\n'] = 0;
090089c4 2484
b8d8561b 2485 /* Return if we have already set `can_be_null'; if we have,
2486 * then the fastmap is irrelevant. Something's wrong here. */
2487 else if (bufp->can_be_null)
2488 return 0;
090089c4 2489
b8d8561b 2490 /* Otherwise, have to check alternative paths. */
2491 break;
090089c4 2492
2493
b8d8561b 2494 case no_op:
2495 case begline:
2496 case endline:
090089c4 2497 case begbuf:
2498 case endbuf:
2499 case wordbound:
2500 case notwordbound:
2501 case wordbeg:
2502 case wordend:
b8d8561b 2503 case push_dummy_failure:
2504 continue;
090089c4 2505
2506
2507 case jump_n:
b8d8561b 2508 case pop_failure_jump:
090089c4 2509 case maybe_pop_jump:
2510 case jump:
b8d8561b 2511 case jump_past_alt:
090089c4 2512 case dummy_failure_jump:
b8d8561b 2513 EXTRACT_NUMBER_AND_INCR(j, p);
2514 p += j;
2515 if (j > 0)
2516 continue;
2517
2518 /* Jump backward implies we just went through the body of a
2519 * loop and matched nothing. Opcode jumped to should be
2520 * `on_failure_jump' or `succeed_n'. Just treat it like an
2521 * ordinary jump. For a * loop, it has pushed its failure
2522 * point already; if so, discard that as redundant. */
2523 if ((re_opcode_t) * p != on_failure_jump
2524 && (re_opcode_t) * p != succeed_n)
2525 continue;
2526
2527 p++;
2528 EXTRACT_NUMBER_AND_INCR(j, p);
2529 p += j;
2530
2531 /* If what's on the stack is where we are now, pop it. */
2532 if (!FAIL_STACK_EMPTY()
2533 && fail_stack.stack[fail_stack.avail - 1] == p)
2534 fail_stack.avail--;
2535
090089c4 2536 continue;
2537
090089c4 2538
b8d8561b 2539 case on_failure_jump:
2540 case on_failure_keep_string_jump:
2541 handle_on_failure_jump:
2542 EXTRACT_NUMBER_AND_INCR(j, p);
2543
2544 /* For some patterns, e.g., `(a?)?', `p+j' here points to the
2545 * end of the pattern. We don't want to push such a point,
2546 * since when we restore it above, entering the switch will
2547 * increment `p' past the end of the pattern. We don't need
2548 * to push such a point since we obviously won't find any more
2549 * fastmap entries beyond `pend'. Such a pattern can match
2550 * the null string, though. */
2551 if (p + j < pend) {
2552 if (!PUSH_PATTERN_OP(p + j, fail_stack))
2553 return -2;
2554 } else
2555 bufp->can_be_null = 1;
2556
2557 if (succeed_n_p) {
2558 EXTRACT_NUMBER_AND_INCR(k, p); /* Skip the n. */
2559 succeed_n_p = false;
2560 }
2561 continue;
090089c4 2562
2563
2564 case succeed_n:
b8d8561b 2565 /* Get to the number of times to succeed. */
2566 p += 2;
2567
2568 /* Increment p past the n for when k != 0. */
2569 EXTRACT_NUMBER_AND_INCR(k, p);
2570 if (k == 0) {
2571 p -= 4;
2572 succeed_n_p = true; /* Spaghetti code alert. */
2573 goto handle_on_failure_jump;
2574 }
2575 continue;
090089c4 2576
2577
2578 case set_number_at:
b8d8561b 2579 p += 4;
2580 continue;
090089c4 2581
2582
2583 case start_memory:
b8d8561b 2584 case stop_memory:
2585 p += 2;
2586 continue;
090089c4 2587
2588
2589 default:
b8d8561b 2590 abort(); /* We have listed all the cases. */
2591 } /* switch *p++ */
2592
2593 /* Getting here means we have found the possible starting
2594 * characters for one path of the pattern -- and that the empty
2595 * string does not match. We need not follow this path further.
2596 * Instead, look at the next alternative (remembered on the
2597 * stack), or quit if no more. The test at the top of the loop
2598 * does these things. */
2599 path_can_be_null = false;
2600 p = pend;
2601 } /* while p */
2602
2603 /* Set `can_be_null' for the last path (also the first path, if the
2604 * pattern is empty). */
2605 bufp->can_be_null |= path_can_be_null;
2606 return 0;
2607} /* re_compile_fastmap */
090089c4 2608\f
090089c4 2609/* Searching routines. */
2610
2611/* Like re_search_2, below, but only one string is specified, and
b8d8561b 2612 * doesn't let you say where to stop matching. */
090089c4 2613
35516333 2614static int
b8d8561b 2615re_search(bufp, string, size, startpos, range, regs)
090089c4 2616 struct re_pattern_buffer *bufp;
2617 const char *string;
2618 int size, startpos, range;
2619 struct re_registers *regs;
2620{
b8d8561b 2621 return re_search_2(bufp, NULL, 0, string, size, startpos, range,
2622 regs, size);
090089c4 2623}
2624
2625
2626/* Using the compiled pattern in BUFP->buffer, first tries to match the
b8d8561b 2627 * virtual concatenation of STRING1 and STRING2, starting first at index
2628 * STARTPOS, then at STARTPOS + 1, and so on.
2629 *
2630 * STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
2631 *
2632 * RANGE is how far to scan while trying to match. RANGE = 0 means try
2633 * only at STARTPOS; in general, the last start tried is STARTPOS +
2634 * RANGE.
2635 *
2636 * In REGS, return the indices of the virtual concatenation of STRING1
2637 * and STRING2 that matched the entire BUFP->buffer and its contained
2638 * subexpressions.
2639 *
2640 * Do not consider matching one past the index STOP in the virtual
2641 * concatenation of STRING1 and STRING2.
2642 *
2643 * We return either the position in the strings at which the match was
2644 * found, -1 if no match, or -2 if error (such as failure
2645 * stack overflow). */
090089c4 2646
35516333 2647static int
b8d8561b 2648re_search_2(bufp, string1, size1, string2, size2, startpos, range, regs, stop)
090089c4 2649 struct re_pattern_buffer *bufp;
2650 const char *string1, *string2;
2651 int size1, size2;
2652 int startpos;
2653 int range;
2654 struct re_registers *regs;
2655 int stop;
2656{
b8d8561b 2657 int val;
2658 register char *fastmap = bufp->fastmap;
2659 register char *translate = bufp->translate;
2660 int total_size = size1 + size2;
2661 int endpos = startpos + range;
2662
2663 /* Check for out-of-range STARTPOS. */
2664 if (startpos < 0 || startpos > total_size)
090089c4 2665 return -1;
090089c4 2666
b8d8561b 2667 /* Fix up RANGE if it might eventually take us outside
2668 * the virtual concatenation of STRING1 and STRING2. */
2669 if (endpos < -1)
2670 range = -1 - startpos;
2671 else if (endpos > total_size)
2672 range = total_size - startpos;
2673
2674 /* If the search isn't to be a backwards one, don't waste time in a
2675 * search for a pattern that must be anchored. */
2676 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == begbuf && range > 0) {
2677 if (startpos > 0)
2678 return -1;
2679 else
2680 range = 1;
2681 }
2682 /* Update the fastmap now if not correct already. */
2683 if (fastmap && !bufp->fastmap_accurate)
2684 if (re_compile_fastmap(bufp) == -2)
2685 return -2;
2686
2687 /* Loop through the string, looking for a place to start matching. */
2688 for (;;) {
2689 /* If a fastmap is supplied, skip quickly over characters that
2690 * cannot be the start of a match. If the pattern can match the
2691 * null string, however, we don't need to skip characters; we want
2692 * the first null string. */
2693 if (fastmap && startpos < total_size && !bufp->can_be_null) {
2694 if (range > 0) { /* Searching forwards. */
2695 register const char *d;
2696 register int lim = 0;
2697 int irange = range;
2698
2699 if (startpos < size1 && startpos + range >= size1)
2700 lim = range - (size1 - startpos);
2701
2702 d = (startpos >= size1 ? string2 - size1 : string1) + startpos;
2703
2704 /* Written out as an if-else to avoid testing `translate'
2705 * inside the loop. */
2706 if (translate)
2707 while (range > lim
2708 && !fastmap[(unsigned char)
2709 translate[(unsigned char) *d++]])
2710 range--;
2711 else
2712 while (range > lim && !fastmap[(unsigned char) *d++])
2713 range--;
2714
2715 startpos += irange - range;
2716 } else { /* Searching backwards. */
2717 register char c = (size1 == 0 || startpos >= size1
2718 ? string2[startpos - size1]
2719 : string1[startpos]);
2720
2721 if (!fastmap[(unsigned char) TRANSLATE(c)])
2722 goto advance;
090089c4 2723 }
2724 }
b8d8561b 2725 /* If can't match the null string, and that's all we have left, fail. */
2726 if (range >= 0 && startpos == total_size && fastmap
2727 && !bufp->can_be_null)
2728 return -1;
090089c4 2729
b8d8561b 2730 val = re_match_2(bufp, string1, size1, string2, size2,
2731 startpos, regs, stop);
2732 if (val >= 0)
2733 return startpos;
2734
2735 if (val == -2)
2736 return -2;
090089c4 2737
b8d8561b 2738 advance:
2739 if (!range)
2740 break;
2741 else if (range > 0) {
2742 range--;
2743 startpos++;
2744 } else {
2745 range++;
2746 startpos--;
2747 }
090089c4 2748 }
b8d8561b 2749 return -1;
2750} /* re_search_2 */
090089c4 2751\f
2752/* Declarations and macros for re_match_2. */
2753
090089c4 2754/* Structure for per-register (a.k.a. per-group) information.
b8d8561b 2755 * This must not be longer than one word, because we push this value
2756 * onto the failure stack. Other register information, such as the
2757 * starting and ending positions (which are addresses), and the list of
2758 * inner groups (which is a bits list) are maintained in separate
2759 * variables.
2760 *
2761 * We are making a (strictly speaking) nonportable assumption here: that
2762 * the compiler will pack our bit fields into something that fits into
2763 * the type of `word', i.e., is something that fits into one item on the
2764 * failure stack. */
2765typedef union {
2766 fail_stack_elt_t word;
2767 struct {
2768 /* This field is one if this group can match the empty string,
2769 * zero if not. If not yet determined, `MATCH_NULL_UNSET_VALUE'. */
090089c4 2770#define MATCH_NULL_UNSET_VALUE 3
b8d8561b 2771 unsigned match_null_string_p:2;
2772 unsigned is_active:1;
2773 unsigned matched_something:1;
2774 unsigned ever_matched_something:1;
2775 } bits;
090089c4 2776} register_info_type;
08bc07d0 2777static boolean alt_match_null_string_p(unsigned char *p, unsigned char *end, register_info_type *reg_info);
2778static boolean common_op_match_null_string_p( unsigned char **p, unsigned char *end, register_info_type *reg_info);
2779static int bcmp_translate(unsigned char const *s1, unsigned char const *s2, register int len, char *translate);
862bc6c0 2780static boolean group_match_null_string_p(unsigned char **p, unsigned char *end, register_info_type *reg_info);
090089c4 2781
2782#define REG_MATCH_NULL_STRING_P(R) ((R).bits.match_null_string_p)
2783#define IS_ACTIVE(R) ((R).bits.is_active)
2784#define MATCHED_SOMETHING(R) ((R).bits.matched_something)
2785#define EVER_MATCHED_SOMETHING(R) ((R).bits.ever_matched_something)
2786
2787
2788/* Call this when have matched a real character; it sets `matched' flags
b8d8561b 2789 * for the subexpressions which we are currently inside. Also records
2790 * that those subexprs have matched. */
090089c4 2791#define SET_REGS_MATCHED() \
2792 do \
2793 { \
2794 unsigned r; \
2795 for (r = lowest_active_reg; r <= highest_active_reg; r++) \
2796 { \
2797 MATCHED_SOMETHING (reg_info[r]) \
2798 = EVER_MATCHED_SOMETHING (reg_info[r]) \
2799 = 1; \
2800 } \
2801 } \
2802 while (0)
2803
2804
2805/* This converts PTR, a pointer into one of the search strings `string1'
b8d8561b 2806 * and `string2' into an offset from the beginning of that string. */
090089c4 2807#define POINTER_TO_OFFSET(ptr) \
2808 (FIRST_STRING_P (ptr) ? (ptr) - string1 : (ptr) - string2 + size1)
2809
2810/* Registers are set to a sentinel when they haven't yet matched. */
2811#define REG_UNSET_VALUE ((char *) -1)
2812#define REG_UNSET(e) ((e) == REG_UNSET_VALUE)
2813
2814
2815/* Macros for dealing with the split strings in re_match_2. */
2816
2817#define MATCHING_IN_FIRST_STRING (dend == end_match_1)
2818
2819/* Call before fetching a character with *d. This switches over to
b8d8561b 2820 * string2 if necessary. */
090089c4 2821#define PREFETCH() \
2822 while (d == dend) \
2823 { \
2824 /* End of string2 => fail. */ \
2825 if (dend == end_match_2) \
2826 goto fail; \
2827 /* End of string1 => advance to string2. */ \
2828 d = string2; \
2829 dend = end_match_2; \
2830 }
2831
2832
2833/* Test if at very beginning or at very end of the virtual concatenation
b8d8561b 2834 * of `string1' and `string2'. If only one string, it's `string2'. */
090089c4 2835#define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
b8d8561b 2836#define AT_STRINGS_END(d) ((d) == end2)
090089c4 2837
2838
2839/* Test if D points to a character which is word-constituent. We have
b8d8561b 2840 * two special cases to check for: if past the end of string1, look at
2841 * the first character in string2; and if before the beginning of
2842 * string2, look at the last character in string1. */
090089c4 2843#define WORDCHAR_P(d) \
2844 (SYNTAX ((d) == end1 ? *string2 \
2845 : (d) == string2 - 1 ? *(end1 - 1) : *(d)) \
2846 == Sword)
2847
2848/* Test if the character before D and the one at D differ with respect
b8d8561b 2849 * to being word-constituent. */
090089c4 2850#define AT_WORD_BOUNDARY(d) \
2851 (AT_STRINGS_BEG (d) || AT_STRINGS_END (d) \
2852 || WORDCHAR_P (d - 1) != WORDCHAR_P (d))
2853
2854
2855/* Free everything we malloc. */
2856#ifdef REGEX_MALLOC
2857#define FREE_VAR(var) if (var) free (var); var = NULL
2858#define FREE_VARIABLES() \
2859 do { \
2860 FREE_VAR (fail_stack.stack); \
2861 FREE_VAR (regstart); \
2862 FREE_VAR (regend); \
2863 FREE_VAR (old_regstart); \
2864 FREE_VAR (old_regend); \
2865 FREE_VAR (best_regstart); \
2866 FREE_VAR (best_regend); \
2867 FREE_VAR (reg_info); \
2868 FREE_VAR (reg_dummy); \
2869 FREE_VAR (reg_info_dummy); \
2870 } while (0)
2871#else /* not REGEX_MALLOC */
2872/* Some MIPS systems (at least) want this to free alloca'd storage. */
2873#define FREE_VARIABLES() alloca (0)
2874#endif /* not REGEX_MALLOC */
2875
2876
2877/* These values must meet several constraints. They must not be valid
b8d8561b 2878 * register values; since we have a limit of 255 registers (because
2879 * we use only one byte in the pattern for the register number), we can
2880 * use numbers larger than 255. They must differ by 1, because of
2881 * NUM_FAILURE_ITEMS above. And the value for the lowest register must
2882 * be larger than the value for the highest register, so we do not try
2883 * to actually save any registers when none are active. */
090089c4 2884#define NO_HIGHEST_ACTIVE_REG (1 << BYTEWIDTH)
2885#define NO_LOWEST_ACTIVE_REG (NO_HIGHEST_ACTIVE_REG + 1)
2886\f
2887/* Matching routines. */
2888
090089c4 2889/* re_match_2 matches the compiled pattern in BUFP against the
b8d8561b 2890 * the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
2891 * and SIZE2, respectively). We start matching at POS, and stop
2892 * matching at STOP.
2893 *
2894 * If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
2895 * store offsets for the substring each group matched in REGS. See the
2896 * documentation for exactly how many groups we fill.
2897 *
2898 * We return -1 if no match, -2 if an internal error (such as the
2899 * failure stack overflowing). Otherwise, we return the length of the
2900 * matched substring. */
090089c4 2901
2902int
b8d8561b 2903re_match_2(bufp, string1, size1, string2, size2, pos, regs, stop)
090089c4 2904 struct re_pattern_buffer *bufp;
2905 const char *string1, *string2;
2906 int size1, size2;
2907 int pos;
2908 struct re_registers *regs;
2909 int stop;
2910{
b8d8561b 2911 /* General temporaries. */
2912 int mcnt;
2913 unsigned char *p1;
2914
2915 /* Just past the end of the corresponding string. */
2916 const char *end1, *end2;
2917
2918 /* Pointers into string1 and string2, just past the last characters in
2919 * each to consider matching. */
2920 const char *end_match_1, *end_match_2;
2921
2922 /* Where we are in the data, and the end of the current string. */
2923 const char *d, *dend;
2924
2925 /* Where we are in the pattern, and the end of the pattern. */
2926 unsigned char *p = bufp->buffer;
2927 register unsigned char *pend = p + bufp->used;
2928
2929 /* We use this to map every character in the string. */
2930 char *translate = bufp->translate;
2931
2932 /* Failure point stack. Each place that can handle a failure further
2933 * down the line pushes a failure point on this stack. It consists of
2934 * restart, regend, and reg_info for all registers corresponding to
2935 * the subexpressions we're currently inside, plus the number of such
2936 * registers, and, finally, two char *'s. The first char * is where
2937 * to resume scanning the pattern; the second one is where to resume
2938 * scanning the strings. If the latter is zero, the failure point is
2939 * a ``dummy''; if a failure happens and the failure point is a dummy,
2940 * it gets discarded and the next next one is tried. */
2941 fail_stack_type fail_stack;
090089c4 2942#ifdef DEBUG
b8d8561b 2943 static unsigned failure_id = 0;
2944 unsigned nfailure_points_pushed = 0, nfailure_points_popped = 0;
090089c4 2945#endif
2946
b8d8561b 2947 /* We fill all the registers internally, independent of what we
2948 * return, for use in backreferences. The number here includes
2949 * an element for register zero. */
2950 unsigned num_regs = bufp->re_nsub + 1;
2951
2952 /* The currently active registers. */
2953 unsigned long lowest_active_reg = NO_LOWEST_ACTIVE_REG;
2954 unsigned long highest_active_reg = NO_HIGHEST_ACTIVE_REG;
2955
2956 /* Information on the contents of registers. These are pointers into
2957 * the input strings; they record just what was matched (on this
2958 * attempt) by a subexpression part of the pattern, that is, the
2959 * regnum-th regstart pointer points to where in the pattern we began
2960 * matching and the regnum-th regend points to right after where we
2961 * stopped matching the regnum-th subexpression. (The zeroth register
2962 * keeps track of what the whole pattern matches.) */
2963 const char **regstart = NULL, **regend = NULL;
2964
2965 /* If a group that's operated upon by a repetition operator fails to
2966 * match anything, then the register for its start will need to be
2967 * restored because it will have been set to wherever in the string we
2968 * are when we last see its open-group operator. Similarly for a
2969 * register's end. */
2970 const char **old_regstart = NULL, **old_regend = NULL;
2971
2972 /* The is_active field of reg_info helps us keep track of which (possibly
2973 * nested) subexpressions we are currently in. The matched_something
2974 * field of reg_info[reg_num] helps us tell whether or not we have
2975 * matched any of the pattern so far this time through the reg_num-th
2976 * subexpression. These two fields get reset each time through any
2977 * loop their register is in. */
2978 register_info_type *reg_info = NULL;
2979
2980 /* The following record the register info as found in the above
2981 * variables when we find a match better than any we've seen before.
2982 * This happens as we backtrack through the failure points, which in
2983 * turn happens only if we have not yet matched the entire string. */
2984 unsigned best_regs_set = false;
2985 const char **best_regstart = NULL, **best_regend = NULL;
2986
2987 /* Logically, this is `best_regend[0]'. But we don't want to have to
2988 * allocate space for that if we're not allocating space for anything
2989 * else (see below). Also, we never need info about register 0 for
2990 * any of the other register vectors, and it seems rather a kludge to
2991 * treat `best_regend' differently than the rest. So we keep track of
2992 * the end of the best match so far in a separate variable. We
2993 * initialize this to NULL so that when we backtrack the first time
2994 * and need to test it, it's not garbage. */
2995 const char *match_end = NULL;
2996
2997 /* Used when we pop values we don't care about. */
2998 const char **reg_dummy = NULL;
2999 register_info_type *reg_info_dummy = NULL;
090089c4 3000
3001#ifdef DEBUG
b8d8561b 3002 /* Counts the total number of registers pushed. */
3003 unsigned num_regs_pushed = 0;
090089c4 3004#endif
3005
b8d8561b 3006 DEBUG_PRINT1("\n\nEntering re_match_2.\n");
3007
3008 INIT_FAIL_STACK();
3009
3010 /* Do not bother to initialize all the register variables if there are
3011 * no groups in the pattern, as it takes a fair amount of time. If
3012 * there are groups, we include space for register 0 (the whole
3013 * pattern), even though we never use it, since it simplifies the
3014 * array indexing. We should fix this. */
3015 if (bufp->re_nsub) {
3016 regstart = REGEX_TALLOC(num_regs, const char *);
3017 regend = REGEX_TALLOC(num_regs, const char *);
3018 old_regstart = REGEX_TALLOC(num_regs, const char *);
3019 old_regend = REGEX_TALLOC(num_regs, const char *);
3020 best_regstart = REGEX_TALLOC(num_regs, const char *);
3021 best_regend = REGEX_TALLOC(num_regs, const char *);
3022 reg_info = REGEX_TALLOC(num_regs, register_info_type);
3023 reg_dummy = REGEX_TALLOC(num_regs, const char *);
3024 reg_info_dummy = REGEX_TALLOC(num_regs, register_info_type);
3025
3026 if (!(regstart && regend && old_regstart && old_regend && reg_info
3027 && best_regstart && best_regend && reg_dummy && reg_info_dummy)) {
3028 FREE_VARIABLES();
3029 return -2;
3030 }
090089c4 3031 }
3032#ifdef REGEX_MALLOC
b8d8561b 3033 else {
3034 /* We must initialize all our variables to NULL, so that
3035 * `FREE_VARIABLES' doesn't try to free them. */
3036 regstart = regend = old_regstart = old_regend = best_regstart
3037 = best_regend = reg_dummy = NULL;
3038 reg_info = reg_info_dummy = (register_info_type *) NULL;
090089c4 3039 }
3040#endif /* REGEX_MALLOC */
3041
b8d8561b 3042 /* The starting position is bogus. */
3043 if (pos < 0 || pos > size1 + size2) {
3044 FREE_VARIABLES();
3045 return -1;
090089c4 3046 }
b8d8561b 3047 /* Initialize subexpression text positions to -1 to mark ones that no
3048 * start_memory/stop_memory has been seen for. Also initialize the
3049 * register information struct. */
3050 for (mcnt = 1; mcnt < num_regs; mcnt++) {
3051 regstart[mcnt] = regend[mcnt]
3052 = old_regstart[mcnt] = old_regend[mcnt] = REG_UNSET_VALUE;
3053
3054 REG_MATCH_NULL_STRING_P(reg_info[mcnt]) = MATCH_NULL_UNSET_VALUE;
3055 IS_ACTIVE(reg_info[mcnt]) = 0;
3056 MATCHED_SOMETHING(reg_info[mcnt]) = 0;
3057 EVER_MATCHED_SOMETHING(reg_info[mcnt]) = 0;
090089c4 3058 }
b8d8561b 3059
3060 /* We move `string1' into `string2' if the latter's empty -- but not if
3061 * `string1' is null. */
3062 if (size2 == 0 && string1 != NULL) {
3063 string2 = string1;
3064 size2 = size1;
3065 string1 = 0;
3066 size1 = 0;
090089c4 3067 }
b8d8561b 3068 end1 = string1 + size1;
3069 end2 = string2 + size2;
3070
3071 /* Compute where to stop matching, within the two strings. */
3072 if (stop <= size1) {
3073 end_match_1 = string1 + stop;
3074 end_match_2 = string2;
3075 } else {
3076 end_match_1 = end1;
3077 end_match_2 = string2 + stop - size1;
090089c4 3078 }
3079
b8d8561b 3080 /* `p' scans through the pattern as `d' scans through the data.
3081 * `dend' is the end of the input string that `d' points within. `d'
3082 * is advanced into the following input string whenever necessary, but
3083 * this happens before fetching; therefore, at the beginning of the
3084 * loop, `d' can be pointing at the end of a string, but it cannot
3085 * equal `string2'. */
3086 if (size1 > 0 && pos <= size1) {
3087 d = string1 + pos;
3088 dend = end_match_1;
3089 } else {
3090 d = string2 + pos - size1;
3091 dend = end_match_2;
090089c4 3092 }
3093
b8d8561b 3094 DEBUG_PRINT1("The compiled pattern is: ");
3095 DEBUG_PRINT_COMPILED_PATTERN(bufp, p, pend);
3096 DEBUG_PRINT1("The string to match is: `");
3097 DEBUG_PRINT_DOUBLE_STRING(d, string1, size1, string2, size2);
3098 DEBUG_PRINT1("'\n");
3099
3100 /* This loops over pattern commands. It exits by returning from the
3101 * function if the match is complete, or it drops through if the match
3102 * fails at this starting point in the input data. */
3103 for (;;) {
3104 DEBUG_PRINT2("\n0x%x: ", p);
3105
3106 if (p == pend) { /* End of pattern means we might have succeeded. */
3107 DEBUG_PRINT1("end of pattern ... ");
3108
3109 /* If we haven't matched the entire string, and we want the
3110 * longest match, try backtracking. */
3111 if (d != end_match_2) {
3112 DEBUG_PRINT1("backtracking.\n");
3113
3114 if (!FAIL_STACK_EMPTY()) { /* More failure points to try. */
3115 boolean same_str_p = (FIRST_STRING_P(match_end)
3116 == MATCHING_IN_FIRST_STRING);
3117
3118 /* If exceeds best match so far, save it. */
3119 if (!best_regs_set
3120 || (same_str_p && d > match_end)
3121 || (!same_str_p && !MATCHING_IN_FIRST_STRING)) {
3122 best_regs_set = true;
3123 match_end = d;
3124
3125 DEBUG_PRINT1("\nSAVING match as best so far.\n");
3126
3127 for (mcnt = 1; mcnt < num_regs; mcnt++) {
3128 best_regstart[mcnt] = regstart[mcnt];
3129 best_regend[mcnt] = regend[mcnt];
3130 }
3131 }
3132 goto fail;
3133 }
3134 /* If no failure points, don't restore garbage. */
3135 else if (best_regs_set) {
3136 restore_best_regs:
3137 /* Restore best match. It may happen that `dend ==
3138 * end_match_1' while the restored d is in string2.
3139 * For example, the pattern `x.*y.*z' against the
3140 * strings `x-' and `y-z-', if the two strings are
3141 * not consecutive in memory. */
3142 DEBUG_PRINT1("Restoring best registers.\n");
3143
3144 d = match_end;
3145 dend = ((d >= string1 && d <= end1)
3146 ? end_match_1 : end_match_2);
3147
3148 for (mcnt = 1; mcnt < num_regs; mcnt++) {
3149 regstart[mcnt] = best_regstart[mcnt];
3150 regend[mcnt] = best_regend[mcnt];
090089c4 3151 }
090089c4 3152 }
b8d8561b 3153 } /* d != end_match_2 */
3154 DEBUG_PRINT1("Accepting match.\n");
3155
3156 /* If caller wants register contents data back, do it. */
3157 if (regs && !bufp->no_sub) {
3158 /* Have the register data arrays been allocated? */
3159 if (bufp->regs_allocated == REGS_UNALLOCATED) { /* No. So allocate them with malloc. We need one
3160 * extra element beyond `num_regs' for the `-1' marker
3161 * GNU code uses. */
3162 regs->num_regs = MAX(RE_NREGS, num_regs + 1);
3163 regs->start = TALLOC(regs->num_regs, regoff_t);
3164 regs->end = TALLOC(regs->num_regs, regoff_t);
3165 if (regs->start == NULL || regs->end == NULL)
3166 return -2;
3167 bufp->regs_allocated = REGS_REALLOCATE;
3168 } else if (bufp->regs_allocated == REGS_REALLOCATE) { /* Yes. If we need more elements than were already
3169 * allocated, reallocate them. If we need fewer, just
3170 * leave it alone. */
3171 if (regs->num_regs < num_regs + 1) {
3172 regs->num_regs = num_regs + 1;
3173 RETALLOC(regs->start, regs->num_regs, regoff_t);
3174 RETALLOC(regs->end, regs->num_regs, regoff_t);
3175 if (regs->start == NULL || regs->end == NULL)
3176 return -2;
3177 }
3178 } else
3179 assert(bufp->regs_allocated == REGS_FIXED);
3180
3181 /* Convert the pointer data in `regstart' and `regend' to
3182 * indices. Register zero has to be set differently,
3183 * since we haven't kept track of any info for it. */
3184 if (regs->num_regs > 0) {
3185 regs->start[0] = pos;
3186 regs->end[0] = (MATCHING_IN_FIRST_STRING ? d - string1
3187 : d - string2 + size1);
3188 }
3189 /* Go through the first `min (num_regs, regs->num_regs)'
3190 * registers, since that is all we initialized. */
3191 for (mcnt = 1; mcnt < MIN(num_regs, regs->num_regs); mcnt++) {
3192 if (REG_UNSET(regstart[mcnt]) || REG_UNSET(regend[mcnt]))
3193 regs->start[mcnt] = regs->end[mcnt] = -1;
3194 else {
3195 regs->start[mcnt] = POINTER_TO_OFFSET(regstart[mcnt]);
3196 regs->end[mcnt] = POINTER_TO_OFFSET(regend[mcnt]);
3197 }
3198 }
3199
3200 /* If the regs structure we return has more elements than
3201 * were in the pattern, set the extra elements to -1. If
3202 * we (re)allocated the registers, this is the case,
3203 * because we always allocate enough to have at least one
3204 * -1 at the end. */
3205 for (mcnt = num_regs; mcnt < regs->num_regs; mcnt++)
3206 regs->start[mcnt] = regs->end[mcnt] = -1;
3207 } /* regs && !bufp->no_sub */
3208 FREE_VARIABLES();
3209 DEBUG_PRINT4("%u failure points pushed, %u popped (%u remain).\n",
3210 nfailure_points_pushed, nfailure_points_popped,
3211 nfailure_points_pushed - nfailure_points_popped);
3212 DEBUG_PRINT2("%u registers pushed.\n", num_regs_pushed);
3213
3214 mcnt = d - pos - (MATCHING_IN_FIRST_STRING
3215 ? string1
3216 : string2 - size1);
3217
3218 DEBUG_PRINT2("Returning %d from re_match_2.\n", mcnt);
3219
3220 return mcnt;
3221 }
3222 /* Otherwise match next pattern command. */
090089c4 3223#ifdef SWITCH_ENUM_BUG
b8d8561b 3224 switch ((int) ((re_opcode_t) * p++))
090089c4 3225#else
b8d8561b 3226 switch ((re_opcode_t) * p++)
090089c4 3227#endif
3228 {
b8d8561b 3229 /* Ignore these. Used to ignore the n of succeed_n's which
3230 * currently have n == 0. */
3231 case no_op:
3232 DEBUG_PRINT1("EXECUTING no_op.\n");
3233 break;
090089c4 3234
3235
b8d8561b 3236 /* Match the next n pattern characters exactly. The following
3237 * byte in the pattern defines n, and the n bytes after that
3238 * are the characters to match. */
090089c4 3239 case exactn:
b8d8561b 3240 mcnt = *p++;
3241 DEBUG_PRINT2("EXECUTING exactn %d.\n", mcnt);
3242
3243 /* This is written out as an if-else so we don't waste time
3244 * testing `translate' inside the loop. */
3245 if (translate) {
3246 do {
3247 PREFETCH();
3248 if (translate[(unsigned char) *d++] != (char) *p++)
3249 goto fail;
090089c4 3250 }
b8d8561b 3251 while (--mcnt);
3252 } else {
3253 do {
3254 PREFETCH();
3255 if (*d++ != (char) *p++)
3256 goto fail;
090089c4 3257 }
b8d8561b 3258 while (--mcnt);
090089c4 3259 }
b8d8561b 3260 SET_REGS_MATCHED();
3261 break;
090089c4 3262
3263
b8d8561b 3264 /* Match any character except possibly a newline or a null. */
090089c4 3265 case anychar:
b8d8561b 3266 DEBUG_PRINT1("EXECUTING anychar.\n");
090089c4 3267
b8d8561b 3268 PREFETCH();
090089c4 3269
b8d8561b 3270 if ((!(bufp->syntax & RE_DOT_NEWLINE) && TRANSLATE(*d) == '\n')
3271 || (bufp->syntax & RE_DOT_NOT_NULL && TRANSLATE(*d) == '\000'))
3272 goto fail;
090089c4 3273
b8d8561b 3274 SET_REGS_MATCHED();
3275 DEBUG_PRINT2(" Matched `%d'.\n", *d);
3276 d++;
3277 break;
090089c4 3278
3279
3280 case charset:
3281 case charset_not:
b8d8561b 3282 {
3283 register unsigned char c;
3284 boolean not = (re_opcode_t) * (p - 1) == charset_not;
3285
3286 DEBUG_PRINT2("EXECUTING charset%s.\n", not ? "_not" : "");
090089c4 3287
b8d8561b 3288 PREFETCH();
3289 c = TRANSLATE(*d); /* The character to match. */
090089c4 3290
b8d8561b 3291 /* Cast to `unsigned' instead of `unsigned char' in case the
3292 * bit list is a full 32 bytes long. */
3293 if (c < (unsigned) (*p * BYTEWIDTH)
3294 && p[1 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
3295 not = !not;
090089c4 3296
b8d8561b 3297 p += 1 + *p;
090089c4 3298
b8d8561b 3299 if (!not)
3300 goto fail;
3301
3302 SET_REGS_MATCHED();
3303 d++;
3304 break;
3305 }
090089c4 3306
b8d8561b 3307
3308 /* The beginning of a group is represented by start_memory.
3309 * The arguments are the register number in the next byte, and the
3310 * number of groups inner to this one in the next. The text
3311 * matched within the group is recorded (in the internal
3312 * registers data structure) under the register number. */
3313 case start_memory:
3314 DEBUG_PRINT3("EXECUTING start_memory %d (%d):\n", *p, p[1]);
3315
3316 /* Find out if this group can match the empty string. */
3317 p1 = p; /* To send to group_match_null_string_p. */
3318
3319 if (REG_MATCH_NULL_STRING_P(reg_info[*p]) == MATCH_NULL_UNSET_VALUE)
3320 REG_MATCH_NULL_STRING_P(reg_info[*p])
3321 = group_match_null_string_p(&p1, pend, reg_info);
3322
3323 /* Save the position in the string where we were the last time
3324 * we were at this open-group operator in case the group is
3325 * operated upon by a repetition operator, e.g., with `(a*)*b'
3326 * against `ab'; then we want to ignore where we are now in
3327 * the string in case this attempt to match fails. */
3328 old_regstart[*p] = REG_MATCH_NULL_STRING_P(reg_info[*p])
3329 ? REG_UNSET(regstart[*p]) ? d : regstart[*p]
3330 : regstart[*p];
3331 DEBUG_PRINT2(" old_regstart: %d\n",
3332 POINTER_TO_OFFSET(old_regstart[*p]));
3333
3334 regstart[*p] = d;
3335 DEBUG_PRINT2(" regstart: %d\n", POINTER_TO_OFFSET(regstart[*p]));
3336
3337 IS_ACTIVE(reg_info[*p]) = 1;
3338 MATCHED_SOMETHING(reg_info[*p]) = 0;
3339
3340 /* This is the new highest active register. */
3341 highest_active_reg = *p;
3342
3343 /* If nothing was active before, this is the new lowest active
3344 * register. */
3345 if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
3346 lowest_active_reg = *p;
3347
3348 /* Move past the register number and inner group count. */
3349 p += 2;
090089c4 3350 break;
b8d8561b 3351
3352
3353 /* The stop_memory opcode represents the end of a group. Its
3354 * arguments are the same as start_memory's: the register
3355 * number, and the number of inner groups. */
090089c4 3356 case stop_memory:
b8d8561b 3357 DEBUG_PRINT3("EXECUTING stop_memory %d (%d):\n", *p, p[1]);
3358
3359 /* We need to save the string position the last time we were at
3360 * this close-group operator in case the group is operated
3361 * upon by a repetition operator, e.g., with `((a*)*(b*)*)*'
3362 * against `aba'; then we want to ignore where we are now in
3363 * the string in case this attempt to match fails. */
3364 old_regend[*p] = REG_MATCH_NULL_STRING_P(reg_info[*p])
3365 ? REG_UNSET(regend[*p]) ? d : regend[*p]
3366 : regend[*p];
3367 DEBUG_PRINT2(" old_regend: %d\n",
3368 POINTER_TO_OFFSET(old_regend[*p]));
3369
3370 regend[*p] = d;
3371 DEBUG_PRINT2(" regend: %d\n", POINTER_TO_OFFSET(regend[*p]));
3372
3373 /* This register isn't active anymore. */
3374 IS_ACTIVE(reg_info[*p]) = 0;
3375
3376 /* If this was the only register active, nothing is active
3377 * anymore. */
3378 if (lowest_active_reg == highest_active_reg) {
3379 lowest_active_reg = NO_LOWEST_ACTIVE_REG;
3380 highest_active_reg = NO_HIGHEST_ACTIVE_REG;
3381 } else { /* We must scan for the new highest active register, since
3382 * it isn't necessarily one less than now: consider
3383 * (a(b)c(d(e)f)g). When group 3 ends, after the f), the
3384 * new highest active register is 1. */
3385 unsigned char r = *p - 1;
3386 while (r > 0 && !IS_ACTIVE(reg_info[r]))
3387 r--;
3388
3389 /* If we end up at register zero, that means that we saved
3390 * the registers as the result of an `on_failure_jump', not
3391 * a `start_memory', and we jumped to past the innermost
3392 * `stop_memory'. For example, in ((.)*) we save
3393 * registers 1 and 2 as a result of the *, but when we pop
3394 * back to the second ), we are at the stop_memory 1.
3395 * Thus, nothing is active. */
3396 if (r == 0) {
3397 lowest_active_reg = NO_LOWEST_ACTIVE_REG;
3398 highest_active_reg = NO_HIGHEST_ACTIVE_REG;
3399 } else
3400 highest_active_reg = r;
3401 }
3402
3403 /* If just failed to match something this time around with a
3404 * group that's operated on by a repetition operator, try to
3405 * force exit from the ``loop'', and restore the register
3406 * information for this group that we had before trying this
3407 * last match. */
3408 if ((!MATCHED_SOMETHING(reg_info[*p])
3409 || (re_opcode_t) p[-3] == start_memory)
3410 && (p + 2) < pend) {
3411 boolean is_a_jump_n = false;
3412
3413 p1 = p + 2;
3414 mcnt = 0;
3415 switch ((re_opcode_t) * p1++) {
3416 case jump_n:
090089c4 3417 is_a_jump_n = true;
b8d8561b 3418 case pop_failure_jump:
3419 case maybe_pop_jump:
3420 case jump:
3421 case dummy_failure_jump:
3422 EXTRACT_NUMBER_AND_INCR(mcnt, p1);
090089c4 3423 if (is_a_jump_n)
b8d8561b 3424 p1 += 2;
3425 break;
3426
3427 default:
3428 /* do nothing */ ;
3429 }
3430 p1 += mcnt;
3431
3432 /* If the next operation is a jump backwards in the pattern
3433 * to an on_failure_jump right before the start_memory
3434 * corresponding to this stop_memory, exit from the loop
3435 * by forcing a failure after pushing on the stack the
3436 * on_failure_jump's jump in the pattern, and d. */
3437 if (mcnt < 0 && (re_opcode_t) * p1 == on_failure_jump
3438 && (re_opcode_t) p1[3] == start_memory && p1[4] == *p) {
3439 /* If this group ever matched anything, then restore
3440 * what its registers were before trying this last
3441 * failed match, e.g., with `(a*)*b' against `ab' for
3442 * regstart[1], and, e.g., with `((a*)*(b*)*)*'
3443 * against `aba' for regend[3].
3444 *
3445 * Also restore the registers for inner groups for,
3446 * e.g., `((a*)(b*))*' against `aba' (register 3 would
3447 * otherwise get trashed). */
3448
3449 if (EVER_MATCHED_SOMETHING(reg_info[*p])) {
3450 unsigned r;
3451
3452 EVER_MATCHED_SOMETHING(reg_info[*p]) = 0;
3453
3454 /* Restore this and inner groups' (if any) registers. */
3455 for (r = *p; r < *p + *(p + 1); r++) {
3456 regstart[r] = old_regstart[r];
3457
3458 /* xx why this test? */
3459 if ((long) old_regend[r] >= (long) regstart[r])
3460 regend[r] = old_regend[r];
3461 }
3462 }
3463 p1++;
3464 EXTRACT_NUMBER_AND_INCR(mcnt, p1);
3465 PUSH_FAILURE_POINT(p1 + mcnt, d, -2);
3466
3467 goto fail;
3468 }
3469 }
3470 /* Move past the register number and the inner group count. */
3471 p += 2;
3472 break;
3473
3474
3475 /* \<digit> has been turned into a `duplicate' command which is
3476 * followed by the numeric value of <digit> as the register number. */
3477 case duplicate:
3478 {
3479 register const char *d2, *dend2;
3480 int regno = *p++; /* Get which register to match against. */
3481 DEBUG_PRINT2("EXECUTING duplicate %d.\n", regno);
3482
3483 /* Can't back reference a group which we've never matched. */
3484 if (REG_UNSET(regstart[regno]) || REG_UNSET(regend[regno]))
3485 goto fail;
3486
3487 /* Where in input to try to start matching. */
3488 d2 = regstart[regno];
3489
3490 /* Where to stop matching; if both the place to start and
3491 * the place to stop matching are in the same string, then
3492 * set to the place to stop, otherwise, for now have to use
3493 * the end of the first string. */
3494
3495 dend2 = ((FIRST_STRING_P(regstart[regno])
3496 == FIRST_STRING_P(regend[regno]))
3497 ? regend[regno] : end_match_1);
3498 for (;;) {
3499 /* If necessary, advance to next segment in register
3500 * contents. */
3501 while (d2 == dend2) {
3502 if (dend2 == end_match_2)
3503 break;
3504 if (dend2 == regend[regno])
3505 break;
3506
3507 /* End of string1 => advance to string2. */
3508 d2 = string2;
3509 dend2 = regend[regno];
3510 }
3511 /* At end of register contents => success */
3512 if (d2 == dend2)
3513 break;
3514
3515 /* If necessary, advance to next segment in data. */
3516 PREFETCH();
3517
3518 /* How many characters left in this segment to match. */
3519 mcnt = dend - d;
3520
3521 /* Want how many consecutive characters we can match in
3522 * one shot, so, if necessary, adjust the count. */
3523 if (mcnt > dend2 - d2)
3524 mcnt = dend2 - d2;
3525
3526 /* Compare that many; failure if mismatch, else move
3527 * past them. */
3528 if (translate
f75662c9 3529 ? bcmp_translate((unsigned char *)d, (unsigned char *)d2, mcnt, translate)
25347664 3530 : memcmp(d, d2, mcnt))
b8d8561b 3531 goto fail;
3532 d += mcnt, d2 += mcnt;
3533 }
3534 }
3535 break;
3536
3537
3538 /* begline matches the empty string at the beginning of the string
3539 * (unless `not_bol' is set in `bufp'), and, if
3540 * `newline_anchor' is set, after newlines. */
090089c4 3541 case begline:
b8d8561b 3542 DEBUG_PRINT1("EXECUTING begline.\n");
3543
3544 if (AT_STRINGS_BEG(d)) {
3545 if (!bufp->not_bol)
3546 break;
3547 } else if (d[-1] == '\n' && bufp->newline_anchor) {
3548 break;
3549 }
3550 /* In all other cases, we fail. */
3551 goto fail;
3552
3553
3554 /* endline is the dual of begline. */
090089c4 3555 case endline:
b8d8561b 3556 DEBUG_PRINT1("EXECUTING endline.\n");
3557
3558 if (AT_STRINGS_END(d)) {
3559 if (!bufp->not_eol)
3560 break;
3561 }
3562 /* We have to ``prefetch'' the next character. */
3563 else if ((d == end1 ? *string2 : *d) == '\n'
3564 && bufp->newline_anchor) {
3565 break;
3566 }
3567 goto fail;
3568
3569
3570 /* Match at the very beginning of the data. */
3571 case begbuf:
3572 DEBUG_PRINT1("EXECUTING begbuf.\n");
3573 if (AT_STRINGS_BEG(d))
3574 break;
3575 goto fail;
3576
3577
3578 /* Match at the very end of the data. */
3579 case endbuf:
3580 DEBUG_PRINT1("EXECUTING endbuf.\n");
3581 if (AT_STRINGS_END(d))
3582 break;
3583 goto fail;
3584
3585
3586 /* on_failure_keep_string_jump is used to optimize `.*\n'. It
3587 * pushes NULL as the value for the string on the stack. Then
3588 * `pop_failure_point' will keep the current value for the
3589 * string, instead of restoring it. To see why, consider
3590 * matching `foo\nbar' against `.*\n'. The .* matches the foo;
3591 * then the . fails against the \n. But the next thing we want
3592 * to do is match the \n against the \n; if we restored the
3593 * string value, we would be back at the foo.
3594 *
3595 * Because this is used only in specific cases, we don't need to
3596 * check all the things that `on_failure_jump' does, to make
3597 * sure the right things get saved on the stack. Hence we don't
3598 * share its code. The only reason to push anything on the
3599 * stack at all is that otherwise we would have to change
3600 * `anychar's code to do something besides goto fail in this
3601 * case; that seems worse than this. */
3602 case on_failure_keep_string_jump:
3603 DEBUG_PRINT1("EXECUTING on_failure_keep_string_jump");
3604
3605 EXTRACT_NUMBER_AND_INCR(mcnt, p);
3606 DEBUG_PRINT3(" %d (to 0x%x):\n", mcnt, p + mcnt);
3607
3608 PUSH_FAILURE_POINT(p + mcnt, NULL, -2);
090089c4 3609 break;
b8d8561b 3610
3611
3612 /* Uses of on_failure_jump:
3613 *
3614 * Each alternative starts with an on_failure_jump that points
3615 * to the beginning of the next alternative. Each alternative
3616 * except the last ends with a jump that in effect jumps past
3617 * the rest of the alternatives. (They really jump to the
3618 * ending jump of the following alternative, because tensioning
3619 * these jumps is a hassle.)
3620 *
3621 * Repeats start with an on_failure_jump that points past both
3622 * the repetition text and either the following jump or
3623 * pop_failure_jump back to this on_failure_jump. */
090089c4 3624 case on_failure_jump:
b8d8561b 3625 on_failure:
3626 DEBUG_PRINT1("EXECUTING on_failure_jump");
3627
3628 EXTRACT_NUMBER_AND_INCR(mcnt, p);
3629 DEBUG_PRINT3(" %d (to 0x%x)", mcnt, p + mcnt);
3630
3631 /* If this on_failure_jump comes right before a group (i.e.,
3632 * the original * applied to a group), save the information
3633 * for that group and all inner ones, so that if we fail back
3634 * to this point, the group's information will be correct.
3635 * For example, in \(a*\)*\1, we need the preceding group,
3636 * and in \(\(a*\)b*\)\2, we need the inner group. */
3637
3638 /* We can't use `p' to check ahead because we push
3639 * a failure point to `p + mcnt' after we do this. */
3640 p1 = p;
3641
3642 /* We need to skip no_op's before we look for the
3643 * start_memory in case this on_failure_jump is happening as
3644 * the result of a completed succeed_n, as in \(a\)\{1,3\}b\1
3645 * against aba. */
3646 while (p1 < pend && (re_opcode_t) * p1 == no_op)
3647 p1++;
3648
3649 if (p1 < pend && (re_opcode_t) * p1 == start_memory) {
3650 /* We have a new highest active register now. This will
3651 * get reset at the start_memory we are about to get to,
3652 * but we will have saved all the registers relevant to
3653 * this repetition op, as described above. */
3654 highest_active_reg = *(p1 + 1) + *(p1 + 2);
3655 if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
3656 lowest_active_reg = *(p1 + 1);
3657 }
3658 DEBUG_PRINT1(":\n");
3659 PUSH_FAILURE_POINT(p + mcnt, d, -2);
3660 break;
3661
090089c4 3662
b8d8561b 3663 /* A smart repeat ends with `maybe_pop_jump'.
3664 * We change it to either `pop_failure_jump' or `jump'. */
3665 case maybe_pop_jump:
3666 EXTRACT_NUMBER_AND_INCR(mcnt, p);
3667 DEBUG_PRINT2("EXECUTING maybe_pop_jump %d.\n", mcnt);
090089c4 3668 {
b8d8561b 3669 register unsigned char *p2 = p;
3670
3671 /* Compare the beginning of the repeat with what in the
3672 * pattern follows its end. If we can establish that there
3673 * is nothing that they would both match, i.e., that we
3674 * would have to backtrack because of (as in, e.g., `a*a')
3675 * then we can change to pop_failure_jump, because we'll
3676 * never have to backtrack.
3677 *
3678 * This is not true in the case of alternatives: in
3679 * `(a|ab)*' we do need to backtrack to the `ab' alternative
3680 * (e.g., if the string was `ab'). But instead of trying to
3681 * detect that here, the alternative has put on a dummy
3682 * failure point which is what we will end up popping. */
3683
3684 /* Skip over open/close-group commands. */
3685 while (p2 + 2 < pend
3686 && ((re_opcode_t) * p2 == stop_memory
3687 || (re_opcode_t) * p2 == start_memory))
3688 p2 += 3; /* Skip over args, too. */
3689
3690 /* If we're at the end of the pattern, we can change. */
3691 if (p2 == pend) {
3692 /* Consider what happens when matching ":\(.*\)"
3693 * against ":/". I don't really understand this code
3694 * yet. */
3695 p[-3] = (unsigned char) pop_failure_jump;
3696 DEBUG_PRINT1
3697 (" End of pattern: change to `pop_failure_jump'.\n");
3698 } else if ((re_opcode_t) * p2 == exactn
3699 || (bufp->newline_anchor && (re_opcode_t) * p2 == endline)) {
3700 register unsigned char c
3701 = *p2 == (unsigned char) endline ? '\n' : p2[2];
3702 p1 = p + mcnt;
3703
3704 /* p1[0] ... p1[2] are the `on_failure_jump' corresponding
3705 * to the `maybe_finalize_jump' of this case. Examine what
3706 * follows. */
3707 if ((re_opcode_t) p1[3] == exactn && p1[5] != c) {
3708 p[-3] = (unsigned char) pop_failure_jump;
3709 DEBUG_PRINT3(" %c != %c => pop_failure_jump.\n",
3710 c, p1[5]);
3711 } else if ((re_opcode_t) p1[3] == charset
3712 || (re_opcode_t) p1[3] == charset_not) {
3713 int not = (re_opcode_t) p1[3] == charset_not;
3714
3715 if (c < (unsigned char) (p1[4] * BYTEWIDTH)
3716 && p1[5 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
3717 not = !not;
3718
3719 /* `not' is equal to 1 if c would match, which means
3720 * that we can't change to pop_failure_jump. */
3721 if (!not) {
3722 p[-3] = (unsigned char) pop_failure_jump;
3723 DEBUG_PRINT1(" No match => pop_failure_jump.\n");
3724 }
3725 }
3726 }
090089c4 3727 }
b8d8561b 3728 p -= 2; /* Point at relative address again. */
3729 if ((re_opcode_t) p[-1] != pop_failure_jump) {
3730 p[-1] = (unsigned char) jump;
3731 DEBUG_PRINT1(" Match => jump.\n");
3732 goto unconditional_jump;
3733 }
3734 /* Note fall through. */
3735
3736
3737 /* The end of a simple repeat has a pop_failure_jump back to
3738 * its matching on_failure_jump, where the latter will push a
3739 * failure point. The pop_failure_jump takes off failure
3740 * points put on by this pop_failure_jump's matching
3741 * on_failure_jump; we got through the pattern to here from the
3742 * matching on_failure_jump, so didn't fail. */
3743 case pop_failure_jump:
3744 {
3745 /* We need to pass separate storage for the lowest and
3746 * highest registers, even though we don't care about the
3747 * actual values. Otherwise, we will restore only one
3748 * register from the stack, since lowest will == highest in
3749 * `pop_failure_point'. */
3750 unsigned long dummy_low_reg, dummy_high_reg;
3751 unsigned char *pdummy;
3752 const char *sdummy;
3753
3754 DEBUG_PRINT1("EXECUTING pop_failure_jump.\n");
3755 POP_FAILURE_POINT(sdummy, pdummy,
3756 dummy_low_reg, dummy_high_reg,
3757 reg_dummy, reg_dummy, reg_info_dummy);
3758 }
3759 /* Note fall through. */
3760
3761
3762 /* Unconditionally jump (without popping any failure points). */
3763 case jump:
3764 unconditional_jump:
3765 EXTRACT_NUMBER_AND_INCR(mcnt, p); /* Get the amount to jump. */
3766 DEBUG_PRINT2("EXECUTING jump %d ", mcnt);
3767 p += mcnt; /* Do the jump. */
3768 DEBUG_PRINT2("(to 0x%x).\n", p);
090089c4 3769 break;
090089c4 3770
b8d8561b 3771
3772 /* We need this opcode so we can detect where alternatives end
3773 * in `group_match_null_string_p' et al. */
3774 case jump_past_alt:
3775 DEBUG_PRINT1("EXECUTING jump_past_alt.\n");
3776 goto unconditional_jump;
3777
3778
3779 /* Normally, the on_failure_jump pushes a failure point, which
3780 * then gets popped at pop_failure_jump. We will end up at
3781 * pop_failure_jump, also, and with a pattern of, say, `a+', we
3782 * are skipping over the on_failure_jump, so we have to push
3783 * something meaningless for pop_failure_jump to pop. */
3784 case dummy_failure_jump:
3785 DEBUG_PRINT1("EXECUTING dummy_failure_jump.\n");
3786 /* It doesn't matter what we push for the string here. What
3787 * the code at `fail' tests is the value for the pattern. */
3788 PUSH_FAILURE_POINT(0, 0, -2);
3789 goto unconditional_jump;
3790
3791
3792 /* At the end of an alternative, we need to push a dummy failure
3793 * point in case we are followed by a `pop_failure_jump', because
3794 * we don't want the failure point for the alternative to be
3795 * popped. For example, matching `(a|ab)*' against `aab'
3796 * requires that we match the `ab' alternative. */
3797 case push_dummy_failure:
3798 DEBUG_PRINT1("EXECUTING push_dummy_failure.\n");
3799 /* See comments just above at `dummy_failure_jump' about the
3800 * two zeroes. */
3801 PUSH_FAILURE_POINT(0, 0, -2);
3802 break;
3803
3804 /* Have to succeed matching what follows at least n times.
3805 * After that, handle like `on_failure_jump'. */
3806 case succeed_n:
3807 EXTRACT_NUMBER(mcnt, p + 2);
3808 DEBUG_PRINT2("EXECUTING succeed_n %d.\n", mcnt);
3809
3810 assert(mcnt >= 0);
3811 /* Originally, this is how many times we HAVE to succeed. */
3812 if (mcnt > 0) {
3813 mcnt--;
3814 p += 2;
3815 STORE_NUMBER_AND_INCR(p, mcnt);
3816 DEBUG_PRINT3(" Setting 0x%x to %d.\n", p, mcnt);
3817 } else if (mcnt == 0) {
3818 DEBUG_PRINT2(" Setting two bytes from 0x%x to no_op.\n", p + 2);
3819 p[2] = (unsigned char) no_op;
3820 p[3] = (unsigned char) no_op;
3821 goto on_failure;
3822 }
3823 break;
3824
3825 case jump_n:
3826 EXTRACT_NUMBER(mcnt, p + 2);
3827 DEBUG_PRINT2("EXECUTING jump_n %d.\n", mcnt);
3828
3829 /* Originally, this is how many times we CAN jump. */
3830 if (mcnt) {
3831 mcnt--;
3832 STORE_NUMBER(p + 2, mcnt);
3833 goto unconditional_jump;
3834 }
3835 /* If don't have to jump any more, skip over the rest of command. */
3836 else
3837 p += 4;
3838 break;
3839
3840 case set_number_at:
3841 {
3842 DEBUG_PRINT1("EXECUTING set_number_at.\n");
3843
3844 EXTRACT_NUMBER_AND_INCR(mcnt, p);
3845 p1 = p + mcnt;
3846 EXTRACT_NUMBER_AND_INCR(mcnt, p);
3847 DEBUG_PRINT3(" Setting 0x%x to %d.\n", p1, mcnt);
3848 STORE_NUMBER(p1, mcnt);
3849 break;
3850 }
3851
3852 case wordbound:
3853 DEBUG_PRINT1("EXECUTING wordbound.\n");
3854 if (AT_WORD_BOUNDARY(d))
3855 break;
090089c4 3856 goto fail;
090089c4 3857
b8d8561b 3858 case notwordbound:
3859 DEBUG_PRINT1("EXECUTING notwordbound.\n");
3860 if (AT_WORD_BOUNDARY(d))
3861 goto fail;
090089c4 3862 break;
b8d8561b 3863
3864 case wordbeg:
3865 DEBUG_PRINT1("EXECUTING wordbeg.\n");
3866 if (WORDCHAR_P(d) && (AT_STRINGS_BEG(d) || !WORDCHAR_P(d - 1)))
3867 break;
3868 goto fail;
090089c4 3869
3870 case wordend:
b8d8561b 3871 DEBUG_PRINT1("EXECUTING wordend.\n");
3872 if (!AT_STRINGS_BEG(d) && WORDCHAR_P(d - 1)
3873 && (!WORDCHAR_P(d) || AT_STRINGS_END(d)))
3874 break;
3875 goto fail;
090089c4 3876
090089c4 3877 case wordchar:
b8d8561b 3878 DEBUG_PRINT1("EXECUTING non-Emacs wordchar.\n");
3879 PREFETCH();
3880 if (!WORDCHAR_P(d))
3881 goto fail;
3882 SET_REGS_MATCHED();
3883 d++;
3884 break;
3885
090089c4 3886 case notwordchar:
b8d8561b 3887 DEBUG_PRINT1("EXECUTING non-Emacs notwordchar.\n");
3888 PREFETCH();
3889 if (WORDCHAR_P(d))
3890 goto fail;
3891 SET_REGS_MATCHED();
3892 d++;
3893 break;
090089c4 3894
b8d8561b 3895 default:
3896 abort();
3897 }
3898 continue; /* Successfully executed one pattern command; keep going. */
3899
3900
3901 /* We goto here if a matching operation fails. */
3902 fail:
3903 if (!FAIL_STACK_EMPTY()) { /* A restart point is known. Restore to that state. */
3904 DEBUG_PRINT1("\nFAIL:\n");
3905 POP_FAILURE_POINT(d, p,
3906 lowest_active_reg, highest_active_reg,
3907 regstart, regend, reg_info);
3908
3909 /* If this failure point is a dummy, try the next one. */
3910 if (!p)
3911 goto fail;
3912
3913 /* If we failed to the end of the pattern, don't examine *p. */
3914 assert(p <= pend);
3915 if (p < pend) {
3916 boolean is_a_jump_n = false;
3917
3918 /* If failed to a backwards jump that's part of a repetition
3919 * loop, need to pop this failure point and use the next one. */
3920 switch ((re_opcode_t) * p) {
3921 case jump_n:
3922 is_a_jump_n = true;
3923 case maybe_pop_jump:
3924 case pop_failure_jump:
3925 case jump:
3926 p1 = p + 1;
3927 EXTRACT_NUMBER_AND_INCR(mcnt, p1);
3928 p1 += mcnt;
3929
3930 if ((is_a_jump_n && (re_opcode_t) * p1 == succeed_n)
3931 || (!is_a_jump_n
3932 && (re_opcode_t) * p1 == on_failure_jump))
3933 goto fail;
3934 break;
3935 default:
3936 /* do nothing */ ;
3937 }
3938 }
3939 if (d >= string1 && d <= end1)
3940 dend = end_match_1;
3941 } else
3942 break; /* Matching at this starting point really fails. */
3943 } /* for (;;) */
090089c4 3944
b8d8561b 3945 if (best_regs_set)
3946 goto restore_best_regs;
090089c4 3947
b8d8561b 3948 FREE_VARIABLES();
090089c4 3949
b8d8561b 3950 return -1; /* Failure to match. */
3951} /* re_match_2 */
090089c4 3952\f
3953/* Subroutine definitions for re_match_2. */
090089c4 3954
3955/* We are passed P pointing to a register number after a start_memory.
b8d8561b 3956 *
3957 * Return true if the pattern up to the corresponding stop_memory can
3958 * match the empty string, and false otherwise.
3959 *
3960 * If we find the matching stop_memory, sets P to point to one past its number.
3961 * Otherwise, sets P to an undefined byte less than or equal to END.
3962 *
3963 * We don't handle duplicates properly (yet). */
090089c4 3964
08bc07d0 3965boolean
3966group_match_null_string_p(unsigned char **p, unsigned char *end, register_info_type *reg_info)
090089c4 3967{
b8d8561b 3968 int mcnt;
3969 /* Point to after the args to the start_memory. */
3970 unsigned char *p1 = *p + 2;
3971
3972 while (p1 < end) {
3973 /* Skip over opcodes that can match nothing, and return true or
3974 * false, as appropriate, when we get to one that can't, or to the
3975 * matching stop_memory. */
3976
3977 switch ((re_opcode_t) * p1) {
3978 /* Could be either a loop or a series of alternatives. */
3979 case on_failure_jump:
3980 p1++;
3981 EXTRACT_NUMBER_AND_INCR(mcnt, p1);
3982
3983 /* If the next operation is not a jump backwards in the
3984 * pattern. */
3985
3986 if (mcnt >= 0) {
3987 /* Go through the on_failure_jumps of the alternatives,
3988 * seeing if any of the alternatives cannot match nothing.
3989 * The last alternative starts with only a jump,
3990 * whereas the rest start with on_failure_jump and end
3991 * with a jump, e.g., here is the pattern for `a|b|c':
3992 *
3993 * /on_failure_jump/0/6/exactn/1/a/jump_past_alt/0/6
3994 * /on_failure_jump/0/6/exactn/1/b/jump_past_alt/0/3
3995 * /exactn/1/c
3996 *
3997 * So, we have to first go through the first (n-1)
3998 * alternatives and then deal with the last one separately. */
3999
4000
4001 /* Deal with the first (n-1) alternatives, which start
4002 * with an on_failure_jump (see above) that jumps to right
4003 * past a jump_past_alt. */
4004
4005 while ((re_opcode_t) p1[mcnt - 3] == jump_past_alt) {
4006 /* `mcnt' holds how many bytes long the alternative
4007 * is, including the ending `jump_past_alt' and
4008 * its number. */
4009
4010 if (!alt_match_null_string_p(p1, p1 + mcnt - 3,
4011 reg_info))
4012 return false;
4013
4014 /* Move to right after this alternative, including the
4015 * jump_past_alt. */
4016 p1 += mcnt;
4017
4018 /* Break if it's the beginning of an n-th alternative
4019 * that doesn't begin with an on_failure_jump. */
4020 if ((re_opcode_t) * p1 != on_failure_jump)
4021 break;
4022
4023 /* Still have to check that it's not an n-th
4024 * alternative that starts with an on_failure_jump. */
4025 p1++;
4026 EXTRACT_NUMBER_AND_INCR(mcnt, p1);
4027 if ((re_opcode_t) p1[mcnt - 3] != jump_past_alt) {
4028 /* Get to the beginning of the n-th alternative. */
4029 p1 -= 3;
4030 break;
4031 }
4032 }
4033
4034 /* Deal with the last alternative: go back and get number
4035 * of the `jump_past_alt' just before it. `mcnt' contains
4036 * the length of the alternative. */
4037 EXTRACT_NUMBER(mcnt, p1 - 2);
4038
4039 if (!alt_match_null_string_p(p1, p1 + mcnt, reg_info))
4040 return false;
4041
4042 p1 += mcnt; /* Get past the n-th alternative. */
4043 } /* if mcnt > 0 */
4044 break;
4045
4046
4047 case stop_memory:
4048 assert(p1[1] == **p);
4049 *p = p1 + 2;
4050 return true;
4051
4052
4053 default:
4054 if (!common_op_match_null_string_p(&p1, end, reg_info))
4055 return false;
4056 }
4057 } /* while p1 < end */
4058
4059 return false;
4060} /* group_match_null_string_p */
090089c4 4061
4062
4063/* Similar to group_match_null_string_p, but doesn't deal with alternatives:
b8d8561b 4064 * It expects P to be the first byte of a single alternative and END one
4065 * byte past the last. The alternative can contain groups. */
4066
08bc07d0 4067boolean
4068alt_match_null_string_p(unsigned char *p, unsigned char *end, register_info_type *reg_info)
090089c4 4069{
b8d8561b 4070 int mcnt;
4071 unsigned char *p1 = p;
4072
4073 while (p1 < end) {
4074 /* Skip over opcodes that can match nothing, and break when we get
4075 * to one that can't. */
4076
4077 switch ((re_opcode_t) * p1) {
4078 /* It's a loop. */
4079 case on_failure_jump:
4080 p1++;
4081 EXTRACT_NUMBER_AND_INCR(mcnt, p1);
4082 p1 += mcnt;
4083 break;
4084
4085 default:
4086 if (!common_op_match_null_string_p(&p1, end, reg_info))
4087 return false;
4088 }
4089 } /* while p1 < end */
4090
4091 return true;
4092} /* alt_match_null_string_p */
090089c4 4093
4094
4095/* Deals with the ops common to group_match_null_string_p and
b8d8561b 4096 * alt_match_null_string_p.
4097 *
4098 * Sets P to one after the op and its arguments, if any. */
090089c4 4099
08bc07d0 4100boolean
4101common_op_match_null_string_p( unsigned char **p, unsigned char *end, register_info_type *reg_info)
090089c4 4102{
b8d8561b 4103 int mcnt;
4104 boolean ret;
4105 int reg_no;
4106 unsigned char *p1 = *p;
090089c4 4107
b8d8561b 4108 switch ((re_opcode_t) * p1++) {
090089c4 4109 case no_op:
4110 case begline:
4111 case endline:
4112 case begbuf:
4113 case endbuf:
4114 case wordbeg:
4115 case wordend:
4116 case wordbound:
4117 case notwordbound:
b8d8561b 4118 break;
090089c4 4119
4120 case start_memory:
b8d8561b 4121 reg_no = *p1;
4122 assert(reg_no > 0 && reg_no <= MAX_REGNUM);
4123 ret = group_match_null_string_p(&p1, end, reg_info);
4124
4125 /* Have to set this here in case we're checking a group which
4126 * contains a group and a back reference to it. */
4127
4128 if (REG_MATCH_NULL_STRING_P(reg_info[reg_no]) == MATCH_NULL_UNSET_VALUE)
4129 REG_MATCH_NULL_STRING_P(reg_info[reg_no]) = ret;
4130
4131 if (!ret)
4132 return false;
4133 break;
4134
4135 /* If this is an optimized succeed_n for zero times, make the jump. */
090089c4 4136 case jump:
b8d8561b 4137 EXTRACT_NUMBER_AND_INCR(mcnt, p1);
4138 if (mcnt >= 0)
4139 p1 += mcnt;
4140 else
4141 return false;
4142 break;
090089c4 4143
4144 case succeed_n:
b8d8561b 4145 /* Get to the number of times to succeed. */
4146 p1 += 2;
4147 EXTRACT_NUMBER_AND_INCR(mcnt, p1);
4148
4149 if (mcnt == 0) {
4150 p1 -= 4;
4151 EXTRACT_NUMBER_AND_INCR(mcnt, p1);
4152 p1 += mcnt;
4153 } else
4154 return false;
4155 break;
4156
4157 case duplicate:
4158 if (!REG_MATCH_NULL_STRING_P(reg_info[*p1]))
4159 return false;
4160 break;
090089c4 4161
4162 case set_number_at:
b8d8561b 4163 p1 += 4;
090089c4 4164
4165 default:
b8d8561b 4166 /* All other opcodes mean we cannot match the empty string. */
4167 return false;
4168 }
090089c4 4169
b8d8561b 4170 *p = p1;
4171 return true;
4172} /* common_op_match_null_string_p */
090089c4 4173
4174
4175/* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
b8d8561b 4176 * bytes; nonzero otherwise. */
4177
08bc07d0 4178int
4179bcmp_translate(unsigned char const *s1, unsigned char const*s2, register int len, char *translate)
090089c4 4180{
08bc07d0 4181 register unsigned char const *p1 = s1, *p2 = s2;
b8d8561b 4182 while (len) {
4183 if (translate[*p1++] != translate[*p2++])
4184 return 1;
4185 len--;
090089c4 4186 }
b8d8561b 4187 return 0;
090089c4 4188}
4189\f
4190/* Entry points for GNU code. */
4191
090089c4 4192\f
35516333 4193/* POSIX.2 functions */
090089c4 4194
4195/* regcomp takes a regular expression as a string and compiles it.
b8d8561b 4196 *
4197 * PREG is a regex_t *. We do not expect any fields to be initialized,
4198 * since POSIX says we shouldn't. Thus, we set
4199 *
4200 * `buffer' to the compiled pattern;
4201 * `used' to the length of the compiled pattern;
4202 * `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
4203 * REG_EXTENDED bit in CFLAGS is set; otherwise, to
4204 * RE_SYNTAX_POSIX_BASIC;
4205 * `newline_anchor' to REG_NEWLINE being set in CFLAGS;
4206 * `fastmap' and `fastmap_accurate' to zero;
4207 * `re_nsub' to the number of subexpressions in PATTERN.
4208 *
4209 * PATTERN is the address of the pattern string.
4210 *
4211 * CFLAGS is a series of bits which affect compilation.
4212 *
4213 * If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
4214 * use POSIX basic syntax.
4215 *
4216 * If REG_NEWLINE is set, then . and [^...] don't match newline.
4217 * Also, regexec will try a match beginning after every newline.
4218 *
4219 * If REG_ICASE is set, then we considers upper- and lowercase
4220 * versions of letters to be equivalent when matching.
4221 *
4222 * If REG_NOSUB is set, then when PREG is passed to regexec, that
4223 * routine will report only success or failure, and nothing about the
4224 * registers.
4225 *
4226 * It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for
4227 * the return codes and their meanings.) */
090089c4 4228
4229int
b8d8561b 4230regcomp(preg, pattern, cflags)
4231 regex_t *preg;
4232 const char *pattern;
4233 int cflags;
090089c4 4234{
b8d8561b 4235 reg_errcode_t ret;
4236 unsigned syntax
090089c4 4237 = (cflags & REG_EXTENDED) ?
b8d8561b 4238 RE_SYNTAX_POSIX_EXTENDED : RE_SYNTAX_POSIX_BASIC;
4239
4240 /* regex_compile will allocate the space for the compiled pattern. */
4241 preg->buffer = 0;
4242 preg->allocated = 0;
4243
4244 /* Don't bother to use a fastmap when searching. This simplifies the
4245 * REG_NEWLINE case: if we used a fastmap, we'd have to put all the
4246 * characters after newlines into the fastmap. This way, we just try
4247 * every character. */
4248 preg->fastmap = 0;
4249
4250 if (cflags & REG_ICASE) {
4251 unsigned i;
4252
4253 preg->translate = (char *) malloc(CHAR_SET_SIZE);
4254 if (preg->translate == NULL)
4255 return (int) REG_ESPACE;
4256
4257 /* Map uppercase characters to corresponding lowercase ones. */
4258 for (i = 0; i < CHAR_SET_SIZE; i++)
4259 preg->translate[i] = ISUPPER(i) ? tolower(i) : i;
4260 } else
4261 preg->translate = NULL;
4262
4263 /* If REG_NEWLINE is set, newlines are treated differently. */
4264 if (cflags & REG_NEWLINE) { /* REG_NEWLINE implies neither . nor [^...] match newline. */
4265 syntax &= ~RE_DOT_NEWLINE;
4266 syntax |= RE_HAT_LISTS_NOT_NEWLINE;
4267 /* It also changes the matching behavior. */
4268 preg->newline_anchor = 1;
4269 } else
4270 preg->newline_anchor = 0;
4271
4272 preg->no_sub = !!(cflags & REG_NOSUB);
4273
4274 /* POSIX says a null character in the pattern terminates it, so we
4275 * can use strlen here in compiling the pattern. */
4276 ret = regex_compile(pattern, strlen(pattern), syntax, preg);
4277
4278 /* POSIX doesn't distinguish between an unmatched open-group and an
4279 * unmatched close-group: both are REG_EPAREN. */
4280 if (ret == REG_ERPAREN)
4281 ret = REG_EPAREN;
4282
4283 return (int) ret;
090089c4 4284}
4285
4286
4287/* regexec searches for a given pattern, specified by PREG, in the
b8d8561b 4288 * string STRING.
4289 *
4290 * If NMATCH is zero or REG_NOSUB was set in the cflags argument to
4291 * `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
4292 * least NMATCH elements, and we set them to the offsets of the
4293 * corresponding matched substrings.
4294 *
4295 * EFLAGS specifies `execution flags' which affect matching: if
4296 * REG_NOTBOL is set, then ^ does not match at the beginning of the
4297 * string; if REG_NOTEOL is set, then $ does not match at the end.
4298 *
4299 * We return 0 if we find a match and REG_NOMATCH if not. */
090089c4 4300
4301int
b8d8561b 4302regexec(preg, string, nmatch, pmatch, eflags)
4303 const regex_t *preg;
4304 const char *string;
4305 size_t nmatch;
4306 regmatch_t pmatch[];
4307 int eflags;
090089c4 4308{
b8d8561b 4309 int ret;
4310 struct re_registers regs;
4311 regex_t private_preg;
4312 int len = strlen(string);
4313 boolean want_reg_info = !preg->no_sub && nmatch > 0;
4314
4315 private_preg = *preg;
4316
4317 private_preg.not_bol = !!(eflags & REG_NOTBOL);
4318 private_preg.not_eol = !!(eflags & REG_NOTEOL);
4319
4320 /* The user has told us exactly how many registers to return
4321 * information about, via `nmatch'. We have to pass that on to the
4322 * matching routines. */
4323 private_preg.regs_allocated = REGS_FIXED;
4324
4325 if (want_reg_info) {
4326 regs.num_regs = nmatch;
4327 regs.start = TALLOC(nmatch, regoff_t);
4328 regs.end = TALLOC(nmatch, regoff_t);
4329 if (regs.start == NULL || regs.end == NULL)
4330 return (int) REG_NOMATCH;
090089c4 4331 }
b8d8561b 4332 /* Perform the searching operation. */
4333 ret = re_search(&private_preg, string, len,
4334 /* start: */ 0, /* range: */ len,
4335 want_reg_info ? &regs : (struct re_registers *) 0);
4336
4337 /* Copy the register information to the POSIX structure. */
4338 if (want_reg_info) {
4339 if (ret >= 0) {
4340 unsigned r;
4341
4342 for (r = 0; r < nmatch; r++) {
4343 pmatch[r].rm_so = regs.start[r];
4344 pmatch[r].rm_eo = regs.end[r];
4345 }
4346 }
4347 /* If we needed the temporary register info, free the space now. */
4348 free(regs.start);
4349 free(regs.end);
090089c4 4350 }
b8d8561b 4351 /* We want zero return to mean success, unlike `re_search'. */
4352 return ret >= 0 ? (int) REG_NOERROR : (int) REG_NOMATCH;
090089c4 4353}
4354
4355
4356/* Returns a message corresponding to an error code, ERRCODE, returned
b8d8561b 4357 * from either regcomp or regexec. We don't use PREG here. */
090089c4 4358
4359size_t
90a9dd4d 4360regerror(int errcode, const regex_t *preg, char *errbuf, size_t errbuf_size)
090089c4 4361{
b8d8561b 4362 const char *msg;
4363 size_t msg_size;
4364
4365 if (errcode < 0
4366 || errcode >= (sizeof(re_error_msg) / sizeof(re_error_msg[0])))
4367 /* Only error codes returned by the rest of the code should be passed
4368 * to this routine. If we are given anything else, or if other regex
4369 * code generates an invalid error code, then the program has a bug.
4370 * Dump core so we can fix it. */
4371 abort();
4372
4373 msg = re_error_msg[errcode];
4374
4375 /* POSIX doesn't require that we do anything in this case, but why
4376 * not be nice. */
4377 if (!msg)
4378 msg = "Success";
4379
4380 msg_size = strlen(msg) + 1; /* Includes the null. */
4381
4382 if (errbuf_size != 0) {
4383 if (msg_size > errbuf_size) {
4384 strncpy(errbuf, msg, errbuf_size - 1);
4385 errbuf[errbuf_size - 1] = 0;
4386 } else
4387 strcpy(errbuf, msg);
090089c4 4388 }
b8d8561b 4389 return msg_size;
090089c4 4390}
4391
4392
4393/* Free dynamically allocated space used by PREG. */
4394
4395void
b8d8561b 4396regfree(preg)
4397 regex_t *preg;
090089c4 4398{
b8d8561b 4399 if (preg->buffer != NULL)
4400 free(preg->buffer);
4401 preg->buffer = NULL;
4402
4403 preg->allocated = 0;
4404 preg->used = 0;
4405
4406 if (preg->fastmap != NULL)
4407 free(preg->fastmap);
4408 preg->fastmap = NULL;
4409 preg->fastmap_accurate = 0;
4410
4411 if (preg->translate != NULL)
4412 free(preg->translate);
4413 preg->translate = NULL;
090089c4 4414}
090089c4 4415\f
4416/*
b8d8561b 4417 * Local variables:
4418 * make-backup-files: t
4419 * version-control: t
4420 * trim-versions-without-asking: nil
4421 * End:
4422 */