1 /*-
2 * SPDX-License-Identifier: BSD-3-Clause
3 *
4 * Copyright (c) 1992, 1993, 1994 Henry Spencer.
5 * Copyright (c) 1992, 1993, 1994
6 * The Regents of the University of California. All rights reserved.
7 *
8 * Copyright (c) 2011 The FreeBSD Foundation
9 *
10 * Portions of this software were developed by David Chisnall
11 * under sponsorship from the FreeBSD Foundation.
12 *
13 * This code is derived from software contributed to Berkeley by
14 * Henry Spencer.
15 *
16 * Redistribution and use in source and binary forms, with or without
17 * modification, are permitted provided that the following conditions
18 * are met:
19 * 1. Redistributions of source code must retain the above copyright
20 * notice, this list of conditions and the following disclaimer.
21 * 2. Redistributions in binary form must reproduce the above copyright
22 * notice, this list of conditions and the following disclaimer in the
23 * documentation and/or other materials provided with the distribution.
24 * 3. Neither the name of the University nor the names of its contributors
25 * may be used to endorse or promote products derived from this software
26 * without specific prior written permission.
27 *
28 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
29 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
30 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
31 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
32 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
33 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
34 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
35 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
36 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
37 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
38 * SUCH DAMAGE.
39 *
40 * @(#)regcomp.c 8.5 (Berkeley) 3/20/94
41 */
42
43 #if defined(LIBC_SCCS) && !defined(lint)
44 static char sccsid[] = "@(#)regcomp.c 8.5 (Berkeley) 3/20/94";
45 #endif /* LIBC_SCCS and not lint */
46 #include <sys/types.h>
47 #include <stdio.h>
48 #include <string.h>
49 #include <ctype.h>
50 #include <limits.h>
51 #include <stdlib.h>
52 #include <regex.h>
53 #include <stdbool.h>
54 #include <wchar.h>
55 #include <wctype.h>
56
57 #ifndef LIBREGEX
58 #include "collate.h"
59 #endif
60
61 #include "utils.h"
62 #include "regex2.h"
63
64 #include "cname.h"
65
66 /*
67 * Branching context, used to keep track of branch state for all of the branch-
68 * aware functions. In addition to keeping track of branch positions for the
69 * p_branch_* functions, we use this to simplify some clumsiness in BREs for
70 * detection of whether ^ is acting as an anchor or being used erroneously and
71 * also for whether we're in a sub-expression or not.
72 */
73 struct branchc {
74 sopno start;
75 sopno back;
76 sopno fwd;
77
78 int nbranch;
79 int nchain;
80 bool outer;
81 bool terminate;
82 };
83
84 /*
85 * parse structure, passed up and down to avoid global variables and
86 * other clumsinesses
87 */
88 struct parse {
89 const char *next; /* next character in RE */
90 const char *end; /* end of string (-> NUL normally) */
91 int error; /* has an error been seen? */
92 int gnuext;
93 sop *strip; /* malloced strip */
94 sopno ssize; /* malloced strip size (allocated) */
95 sopno slen; /* malloced strip length (used) */
96 int ncsalloc; /* number of csets allocated */
97 struct re_guts *g;
98 # define NPAREN 10 /* we need to remember () 1-9 for back refs */
99 sopno pbegin[NPAREN]; /* -> ( ([0] unused) */
100 sopno pend[NPAREN]; /* -> ) ([0] unused) */
101 bool allowbranch; /* can this expression branch? */
102 bool bre; /* convenience; is this a BRE? */
103 int pflags; /* other parsing flags -- legacy escapes? */
104 bool (*parse_expr)(struct parse *, struct branchc *);
105 void (*pre_parse)(struct parse *, struct branchc *);
106 void (*post_parse)(struct parse *, struct branchc *);
107 };
108
109 #define PFLAG_LEGACY_ESC 0x00000001
110
111 /* ========= begin header generated by ./mkh ========= */
112 #ifdef __cplusplus
113 extern "C" {
114 #endif
115
116 /* === regcomp.c === */
117 static bool p_ere_exp(struct parse *p, struct branchc *bc);
118 static void p_str(struct parse *p);
119 static int p_branch_eat_delim(struct parse *p, struct branchc *bc);
120 static void p_branch_ins_offset(struct parse *p, struct branchc *bc);
121 static void p_branch_fix_tail(struct parse *p, struct branchc *bc);
122 static bool p_branch_empty(struct parse *p, struct branchc *bc);
123 static bool p_branch_do(struct parse *p, struct branchc *bc);
124 static void p_bre_pre_parse(struct parse *p, struct branchc *bc);
125 static void p_bre_post_parse(struct parse *p, struct branchc *bc);
126 static void p_re(struct parse *p, int end1, int end2);
127 static bool p_simp_re(struct parse *p, struct branchc *bc);
128 static int p_count(struct parse *p);
129 static void p_bracket(struct parse *p);
130 static int p_range_cmp(wchar_t c1, wchar_t c2);
131 static void p_b_term(struct parse *p, cset *cs);
132 static int p_b_pseudoclass(struct parse *p, char c);
133 static void p_b_cclass(struct parse *p, cset *cs);
134 static void p_b_cclass_named(struct parse *p, cset *cs, const char[]);
135 static void p_b_eclass(struct parse *p, cset *cs);
136 static wint_t p_b_symbol(struct parse *p);
137 static wint_t p_b_coll_elem(struct parse *p, wint_t endc);
138 static bool may_escape(struct parse *p, const wint_t ch);
139 static wint_t othercase(wint_t ch);
140 static void bothcases(struct parse *p, wint_t ch);
141 static void ordinary(struct parse *p, wint_t ch);
142 static void nonnewline(struct parse *p);
143 static void repeat(struct parse *p, sopno start, int from, int to);
144 static int seterr(struct parse *p, int e);
145 static cset *allocset(struct parse *p);
146 static void freeset(struct parse *p, cset *cs);
147 static void CHadd(struct parse *p, cset *cs, wint_t ch);
148 static void CHaddrange(struct parse *p, cset *cs, wint_t min, wint_t max);
149 static void CHaddtype(struct parse *p, cset *cs, wctype_t wct);
150 static wint_t singleton(cset *cs);
151 static sopno dupl(struct parse *p, sopno start, sopno finish);
152 static void doemit(struct parse *p, sop op, size_t opnd);
153 static void doinsert(struct parse *p, sop op, size_t opnd, sopno pos);
154 static void dofwd(struct parse *p, sopno pos, sop value);
155 static int enlarge(struct parse *p, sopno size);
156 static void stripsnug(struct parse *p, struct re_guts *g);
157 static void findmust(struct parse *p, struct re_guts *g);
158 static int altoffset(sop *scan, int offset);
159 static void computejumps(struct parse *p, struct re_guts *g);
160 static void computematchjumps(struct parse *p, struct re_guts *g);
161 static sopno pluscount(struct parse *p, struct re_guts *g);
162 static wint_t wgetnext(struct parse *p);
163
164 #ifdef __cplusplus
165 }
166 #endif
167 /* ========= end header generated by ./mkh ========= */
168
169 static char nuls[10]; /* place to point scanner in event of error */
170
171 /*
172 * macros for use with parse structure
173 * BEWARE: these know that the parse structure is named `p' !!!
174 */
175 #define PEEK() (*p->next)
176 #define PEEK2() (*(p->next+1))
177 #define MORE() (p->end - p->next > 0)
178 #define MORE2() (p->end - p->next > 1)
179 #define SEE(c) (MORE() && PEEK() == (c))
180 #define SEETWO(a, b) (MORE2() && PEEK() == (a) && PEEK2() == (b))
181 #define SEESPEC(a) (p->bre ? SEETWO('\\', a) : SEE(a))
182 #define EAT(c) ((SEE(c)) ? (NEXT(), 1) : 0)
183 #define EATTWO(a, b) ((SEETWO(a, b)) ? (NEXT2(), 1) : 0)
184 #define EATSPEC(a) (p->bre ? EATTWO('\\', a) : EAT(a))
185 #define NEXT() (p->next++)
186 #define NEXT2() (p->next += 2)
187 #define NEXTn(n) (p->next += (n))
188 #define GETNEXT() (*p->next++)
189 #define WGETNEXT() wgetnext(p)
190 #define SETERROR(e) seterr(p, (e))
191 #define REQUIRE(co, e) ((co) || SETERROR(e))
192 #define MUSTSEE(c, e) (REQUIRE(MORE() && PEEK() == (c), e))
193 #define MUSTEAT(c, e) (REQUIRE(MORE() && GETNEXT() == (c), e))
194 #define MUSTNOTSEE(c, e) (REQUIRE(!MORE() || PEEK() != (c), e))
195 #define EMIT(op, sopnd) doemit(p, (sop)(op), (size_t)(sopnd))
196 #define INSERT(op, pos) doinsert(p, (sop)(op), HERE()-(pos)+1, pos)
197 #define AHEAD(pos) dofwd(p, pos, HERE()-(pos))
198 #define ASTERN(sop, pos) EMIT(sop, HERE()-pos)
199 #define HERE() (p->slen)
200 #define THERE() (p->slen - 1)
201 #define THERETHERE() (p->slen - 2)
202 #define DROP(n) (p->slen -= (n))
203
204 /* Macro used by computejump()/computematchjump() */
205 #define MIN(a,b) ((a)<(b)?(a):(b))
206
207 static int /* 0 success, otherwise REG_something */
regcomp_internal(regex_t * __restrict preg,const char * __restrict pattern,int cflags,int pflags)208 regcomp_internal(regex_t * __restrict preg,
209 const char * __restrict pattern,
210 int cflags, int pflags)
211 {
212 struct parse pa;
213 struct re_guts *g;
214 struct parse *p = &pa;
215 int i;
216 size_t len;
217 size_t maxlen;
218 #ifdef REDEBUG
219 # define GOODFLAGS(f) (f)
220 #else
221 # define GOODFLAGS(f) ((f)&~REG_DUMP)
222 #endif
223
224 cflags = GOODFLAGS(cflags);
225 if ((cflags®_EXTENDED) && (cflags®_NOSPEC))
226 return(REG_INVARG);
227
228 if (cflags®_PEND) {
229 if (preg->re_endp < pattern)
230 return(REG_INVARG);
231 len = preg->re_endp - pattern;
232 } else
233 len = strlen(pattern);
234
235 /* do the mallocs early so failure handling is easy */
236 g = (struct re_guts *)malloc(sizeof(struct re_guts));
237 if (g == NULL)
238 return(REG_ESPACE);
239 /*
240 * Limit the pattern space to avoid a 32-bit overflow on buffer
241 * extension. Also avoid any signed overflow in case of conversion
242 * so make the real limit based on a 31-bit overflow.
243 *
244 * Likely not applicable on 64-bit systems but handle the case
245 * generically (who are we to stop people from using ~715MB+
246 * patterns?).
247 */
248 maxlen = ((size_t)-1 >> 1) / sizeof(sop) * 2 / 3;
249 if (len >= maxlen) {
250 free((char *)g);
251 return(REG_ESPACE);
252 }
253 p->ssize = len/(size_t)2*(size_t)3 + (size_t)1; /* ugh */
254 assert(p->ssize >= len);
255
256 p->strip = (sop *)malloc(p->ssize * sizeof(sop));
257 p->slen = 0;
258 if (p->strip == NULL) {
259 free((char *)g);
260 return(REG_ESPACE);
261 }
262
263 /* set things up */
264 p->g = g;
265 p->next = pattern; /* convenience; we do not modify it */
266 p->end = p->next + len;
267 p->error = 0;
268 p->ncsalloc = 0;
269 p->pflags = pflags;
270 for (i = 0; i < NPAREN; i++) {
271 p->pbegin[i] = 0;
272 p->pend[i] = 0;
273 }
274 #ifdef LIBREGEX
275 if (cflags®_POSIX) {
276 p->gnuext = false;
277 p->allowbranch = (cflags & REG_EXTENDED) != 0;
278 } else
279 p->gnuext = p->allowbranch = true;
280 #else
281 p->gnuext = false;
282 p->allowbranch = (cflags & REG_EXTENDED) != 0;
283 #endif
284 if (cflags & REG_EXTENDED) {
285 p->bre = false;
286 p->parse_expr = p_ere_exp;
287 p->pre_parse = NULL;
288 p->post_parse = NULL;
289 } else {
290 p->bre = true;
291 p->parse_expr = p_simp_re;
292 p->pre_parse = p_bre_pre_parse;
293 p->post_parse = p_bre_post_parse;
294 }
295 g->sets = NULL;
296 g->ncsets = 0;
297 g->cflags = cflags;
298 g->iflags = 0;
299 g->nbol = 0;
300 g->neol = 0;
301 g->must = NULL;
302 g->moffset = -1;
303 g->charjump = NULL;
304 g->matchjump = NULL;
305 g->mlen = 0;
306 g->nsub = 0;
307 g->backrefs = 0;
308
309 /* do it */
310 EMIT(OEND, 0);
311 g->firststate = THERE();
312 if (cflags & REG_NOSPEC)
313 p_str(p);
314 else
315 p_re(p, OUT, OUT);
316 EMIT(OEND, 0);
317 g->laststate = THERE();
318
319 /* tidy up loose ends and fill things in */
320 stripsnug(p, g);
321 findmust(p, g);
322 /* only use Boyer-Moore algorithm if the pattern is bigger
323 * than three characters
324 */
325 if(g->mlen > 3) {
326 computejumps(p, g);
327 computematchjumps(p, g);
328 if(g->matchjump == NULL && g->charjump != NULL) {
329 free(g->charjump);
330 g->charjump = NULL;
331 }
332 }
333 g->nplus = pluscount(p, g);
334 g->magic = MAGIC2;
335 preg->re_nsub = g->nsub;
336 preg->re_g = g;
337 preg->re_magic = MAGIC1;
338 #ifndef REDEBUG
339 /* not debugging, so can't rely on the assert() in regexec() */
340 if (g->iflags&BAD)
341 SETERROR(REG_ASSERT);
342 #endif
343
344 /* win or lose, we're done */
345 if (p->error != 0) /* lose */
346 regfree(preg);
347 return(p->error);
348 }
349
350 /*
351 - regcomp - interface for parser and compilation
352 = extern int regcomp(regex_t *, const char *, int);
353 = #define REG_BASIC 0000
354 = #define REG_EXTENDED 0001
355 = #define REG_ICASE 0002
356 = #define REG_NOSUB 0004
357 = #define REG_NEWLINE 0010
358 = #define REG_NOSPEC 0020
359 = #define REG_PEND 0040
360 = #define REG_DUMP 0200
361 */
362 int /* 0 success, otherwise REG_something */
regcomp(regex_t * __restrict preg,const char * __restrict pattern,int cflags)363 regcomp(regex_t * __restrict preg,
364 const char * __restrict pattern,
365 int cflags)
366 {
367
368 return (regcomp_internal(preg, pattern, cflags, 0));
369 }
370
371 #ifndef LIBREGEX
372 /*
373 * Legacy interface that requires more lax escaping behavior.
374 */
375 int
freebsd12_regcomp(regex_t * __restrict preg,const char * __restrict pattern,int cflags,int pflags)376 freebsd12_regcomp(regex_t * __restrict preg,
377 const char * __restrict pattern,
378 int cflags, int pflags)
379 {
380
381 return (regcomp_internal(preg, pattern, cflags, PFLAG_LEGACY_ESC));
382 }
383
384 __sym_compat(regcomp, freebsd12_regcomp, FBSD_1.0);
385 #endif /* !LIBREGEX */
386
387 /*
388 - p_ere_exp - parse one subERE, an atom possibly followed by a repetition op,
389 - return whether we should terminate or not
390 == static bool p_ere_exp(struct parse *p);
391 */
392 static bool
p_ere_exp(struct parse * p,struct branchc * bc)393 p_ere_exp(struct parse *p, struct branchc *bc)
394 {
395 char c;
396 wint_t wc;
397 sopno pos;
398 int count;
399 int count2;
400 #ifdef LIBREGEX
401 int i;
402 int handled;
403 #endif
404 sopno subno;
405 int wascaret = 0;
406
407 (void)bc;
408 assert(MORE()); /* caller should have ensured this */
409 c = GETNEXT();
410
411 #ifdef LIBREGEX
412 handled = 0;
413 #endif
414 pos = HERE();
415 switch (c) {
416 case '(':
417 (void)REQUIRE(MORE(), REG_EPAREN);
418 p->g->nsub++;
419 subno = p->g->nsub;
420 if (subno < NPAREN)
421 p->pbegin[subno] = HERE();
422 EMIT(OLPAREN, subno);
423 if (!SEE(')'))
424 p_re(p, ')', IGN);
425 if (subno < NPAREN) {
426 p->pend[subno] = HERE();
427 assert(p->pend[subno] != 0);
428 }
429 EMIT(ORPAREN, subno);
430 (void)MUSTEAT(')', REG_EPAREN);
431 break;
432 #ifndef POSIX_MISTAKE
433 case ')': /* happens only if no current unmatched ( */
434 /*
435 * You may ask, why the ifndef? Because I didn't notice
436 * this until slightly too late for 1003.2, and none of the
437 * other 1003.2 regular-expression reviewers noticed it at
438 * all. So an unmatched ) is legal POSIX, at least until
439 * we can get it fixed.
440 */
441 SETERROR(REG_EPAREN);
442 break;
443 #endif
444 case '^':
445 EMIT(OBOL, 0);
446 p->g->iflags |= USEBOL;
447 p->g->nbol++;
448 wascaret = 1;
449 break;
450 case '$':
451 EMIT(OEOL, 0);
452 p->g->iflags |= USEEOL;
453 p->g->neol++;
454 break;
455 case '|':
456 SETERROR(REG_EMPTY);
457 break;
458 case '*':
459 case '+':
460 case '?':
461 case '{':
462 SETERROR(REG_BADRPT);
463 break;
464 case '.':
465 if (p->g->cflags®_NEWLINE)
466 nonnewline(p);
467 else
468 EMIT(OANY, 0);
469 break;
470 case '[':
471 p_bracket(p);
472 break;
473 case '\\':
474 (void)REQUIRE(MORE(), REG_EESCAPE);
475 wc = WGETNEXT();
476 #ifdef LIBREGEX
477 if (p->gnuext) {
478 handled = 1;
479 switch (wc) {
480 case '`':
481 EMIT(OBOS, 0);
482 break;
483 case '\'':
484 EMIT(OEOS, 0);
485 break;
486 case 'B':
487 EMIT(ONWBND, 0);
488 break;
489 case 'b':
490 EMIT(OWBND, 0);
491 break;
492 case 'W':
493 case 'w':
494 case 'S':
495 case 's':
496 p_b_pseudoclass(p, wc);
497 break;
498 case '1':
499 case '2':
500 case '3':
501 case '4':
502 case '5':
503 case '6':
504 case '7':
505 case '8':
506 case '9':
507 i = wc - '0';
508 assert(i < NPAREN);
509 if (p->pend[i] != 0) {
510 assert(i <= p->g->nsub);
511 EMIT(OBACK_, i);
512 assert(p->pbegin[i] != 0);
513 assert(OP(p->strip[p->pbegin[i]]) == OLPAREN);
514 assert(OP(p->strip[p->pend[i]]) == ORPAREN);
515 (void) dupl(p, p->pbegin[i]+1, p->pend[i]);
516 EMIT(O_BACK, i);
517 } else
518 SETERROR(REG_ESUBREG);
519 p->g->backrefs = 1;
520 break;
521 default:
522 handled = 0;
523 }
524 /* Don't proceed to the POSIX bits if we've already handled it */
525 if (handled)
526 break;
527 }
528 #endif
529 switch (wc) {
530 case '<':
531 EMIT(OBOW, 0);
532 break;
533 case '>':
534 EMIT(OEOW, 0);
535 break;
536 default:
537 if (may_escape(p, wc))
538 ordinary(p, wc);
539 else
540 SETERROR(REG_EESCAPE);
541 break;
542 }
543 break;
544 default:
545 if (p->error != 0)
546 return (false);
547 p->next--;
548 wc = WGETNEXT();
549 ordinary(p, wc);
550 break;
551 }
552
553 if (!MORE())
554 return (false);
555 c = PEEK();
556 /* we call { a repetition if followed by a digit */
557 if (!( c == '*' || c == '+' || c == '?' || c == '{'))
558 return (false); /* no repetition, we're done */
559 else if (c == '{')
560 (void)REQUIRE(MORE2() && \
561 (isdigit((uch)PEEK2()) || PEEK2() == ','), REG_BADRPT);
562 NEXT();
563
564 (void)REQUIRE(!wascaret, REG_BADRPT);
565 switch (c) {
566 case '*': /* implemented as +? */
567 /* this case does not require the (y|) trick, noKLUDGE */
568 INSERT(OPLUS_, pos);
569 ASTERN(O_PLUS, pos);
570 INSERT(OQUEST_, pos);
571 ASTERN(O_QUEST, pos);
572 break;
573 case '+':
574 INSERT(OPLUS_, pos);
575 ASTERN(O_PLUS, pos);
576 break;
577 case '?':
578 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
579 INSERT(OCH_, pos); /* offset slightly wrong */
580 ASTERN(OOR1, pos); /* this one's right */
581 AHEAD(pos); /* fix the OCH_ */
582 EMIT(OOR2, 0); /* offset very wrong... */
583 AHEAD(THERE()); /* ...so fix it */
584 ASTERN(O_CH, THERETHERE());
585 break;
586 case '{':
587 count = p_count(p);
588 if (EAT(',')) {
589 if (isdigit((uch)PEEK())) {
590 count2 = p_count(p);
591 (void)REQUIRE(count <= count2, REG_BADBR);
592 } else /* single number with comma */
593 count2 = INFINITY;
594 } else /* just a single number */
595 count2 = count;
596 repeat(p, pos, count, count2);
597 if (!EAT('}')) { /* error heuristics */
598 while (MORE() && PEEK() != '}')
599 NEXT();
600 (void)REQUIRE(MORE(), REG_EBRACE);
601 SETERROR(REG_BADBR);
602 }
603 break;
604 }
605
606 if (!MORE())
607 return (false);
608 c = PEEK();
609 if (!( c == '*' || c == '+' || c == '?' ||
610 (c == '{' && MORE2() && isdigit((uch)PEEK2())) ) )
611 return (false);
612 SETERROR(REG_BADRPT);
613 return (false);
614 }
615
616 /*
617 - p_str - string (no metacharacters) "parser"
618 == static void p_str(struct parse *p);
619 */
620 static void
p_str(struct parse * p)621 p_str(struct parse *p)
622 {
623 (void)REQUIRE(MORE(), REG_EMPTY);
624 while (MORE())
625 ordinary(p, WGETNEXT());
626 }
627
628 /*
629 * Eat consecutive branch delimiters for the kind of expression that we are
630 * parsing, return the number of delimiters that we ate.
631 */
632 static int
p_branch_eat_delim(struct parse * p,struct branchc * bc)633 p_branch_eat_delim(struct parse *p, struct branchc *bc)
634 {
635 int nskip;
636
637 (void)bc;
638 nskip = 0;
639 while (EATSPEC('|'))
640 ++nskip;
641 return (nskip);
642 }
643
644 /*
645 * Insert necessary branch book-keeping operations. This emits a
646 * bogus 'next' offset, since we still have more to parse
647 */
648 static void
p_branch_ins_offset(struct parse * p,struct branchc * bc)649 p_branch_ins_offset(struct parse *p, struct branchc *bc)
650 {
651
652 if (bc->nbranch == 0) {
653 INSERT(OCH_, bc->start); /* offset is wrong */
654 bc->fwd = bc->start;
655 bc->back = bc->start;
656 }
657
658 ASTERN(OOR1, bc->back);
659 bc->back = THERE();
660 AHEAD(bc->fwd); /* fix previous offset */
661 bc->fwd = HERE();
662 EMIT(OOR2, 0); /* offset is very wrong */
663 ++bc->nbranch;
664 }
665
666 /*
667 * Fix the offset of the tail branch, if we actually had any branches.
668 * This is to correct the bogus placeholder offset that we use.
669 */
670 static void
p_branch_fix_tail(struct parse * p,struct branchc * bc)671 p_branch_fix_tail(struct parse *p, struct branchc *bc)
672 {
673
674 /* Fix bogus offset at the tail if we actually have branches */
675 if (bc->nbranch > 0) {
676 AHEAD(bc->fwd);
677 ASTERN(O_CH, bc->back);
678 }
679 }
680
681 /*
682 * Signal to the parser that an empty branch has been encountered; this will,
683 * in the future, be used to allow for more permissive behavior with empty
684 * branches. The return value should indicate whether parsing may continue
685 * or not.
686 */
687 static bool
p_branch_empty(struct parse * p,struct branchc * bc)688 p_branch_empty(struct parse *p, struct branchc *bc)
689 {
690
691 (void)bc;
692 SETERROR(REG_EMPTY);
693 return (false);
694 }
695
696 /*
697 * Take care of any branching requirements. This includes inserting the
698 * appropriate branching instructions as well as eating all of the branch
699 * delimiters until we either run out of pattern or need to parse more pattern.
700 */
701 static bool
p_branch_do(struct parse * p,struct branchc * bc)702 p_branch_do(struct parse *p, struct branchc *bc)
703 {
704 int ate = 0;
705
706 ate = p_branch_eat_delim(p, bc);
707 if (ate == 0)
708 return (false);
709 else if ((ate > 1 || (bc->outer && !MORE())) && !p_branch_empty(p, bc))
710 /*
711 * Halt parsing only if we have an empty branch and p_branch_empty
712 * indicates that we must not continue. In the future, this will not
713 * necessarily be an error.
714 */
715 return (false);
716 p_branch_ins_offset(p, bc);
717
718 return (true);
719 }
720
721 static void
p_bre_pre_parse(struct parse * p,struct branchc * bc)722 p_bre_pre_parse(struct parse *p, struct branchc *bc)
723 {
724
725 (void) bc;
726 /*
727 * Does not move cleanly into expression parser because of
728 * ordinary interpration of * at the beginning position of
729 * an expression.
730 */
731 if (EAT('^')) {
732 EMIT(OBOL, 0);
733 p->g->iflags |= USEBOL;
734 p->g->nbol++;
735 }
736 }
737
738 static void
p_bre_post_parse(struct parse * p,struct branchc * bc)739 p_bre_post_parse(struct parse *p, struct branchc *bc)
740 {
741
742 /* Expression is terminating due to EOL token */
743 if (bc->terminate) {
744 DROP(1);
745 EMIT(OEOL, 0);
746 p->g->iflags |= USEEOL;
747 p->g->neol++;
748 }
749 }
750
751 /*
752 - p_re - Top level parser, concatenation and BRE anchoring
753 == static void p_re(struct parse *p, int end1, int end2);
754 * Giving end1 as OUT essentially eliminates the end1/end2 check.
755 *
756 * This implementation is a bit of a kludge, in that a trailing $ is first
757 * taken as an ordinary character and then revised to be an anchor.
758 * The amount of lookahead needed to avoid this kludge is excessive.
759 */
760 static void
p_re(struct parse * p,int end1,int end2)761 p_re(struct parse *p,
762 int end1, /* first terminating character */
763 int end2) /* second terminating character; ignored for EREs */
764 {
765 struct branchc bc;
766
767 bc.nbranch = 0;
768 if (end1 == OUT && end2 == OUT)
769 bc.outer = true;
770 else
771 bc.outer = false;
772 #define SEEEND() (!p->bre ? SEE(end1) : SEETWO(end1, end2))
773 for (;;) {
774 bc.start = HERE();
775 bc.nchain = 0;
776 bc.terminate = false;
777 if (p->pre_parse != NULL)
778 p->pre_parse(p, &bc);
779 while (MORE() && (!p->allowbranch || !SEESPEC('|')) && !SEEEND()) {
780 bc.terminate = p->parse_expr(p, &bc);
781 ++bc.nchain;
782 }
783 if (p->post_parse != NULL)
784 p->post_parse(p, &bc);
785 (void) REQUIRE(p->gnuext || HERE() != bc.start, REG_EMPTY);
786 #ifdef LIBREGEX
787 if (HERE() == bc.start && !p_branch_empty(p, &bc))
788 break;
789 #endif
790 if (!p->allowbranch)
791 break;
792 /*
793 * p_branch_do's return value indicates whether we should
794 * continue parsing or not. This is both for correctness and
795 * a slight optimization, because it will check if we've
796 * encountered an empty branch or the end of the string
797 * immediately following a branch delimiter.
798 */
799 if (!p_branch_do(p, &bc))
800 break;
801 }
802 #undef SEE_END
803 if (p->allowbranch)
804 p_branch_fix_tail(p, &bc);
805 assert(!MORE() || SEE(end1));
806 }
807
808 /*
809 - p_simp_re - parse a simple RE, an atom possibly followed by a repetition
810 == static bool p_simp_re(struct parse *p, struct branchc *bc);
811 */
812 static bool /* was the simple RE an unbackslashed $? */
p_simp_re(struct parse * p,struct branchc * bc)813 p_simp_re(struct parse *p, struct branchc *bc)
814 {
815 int c;
816 int cc; /* convenient/control character */
817 int count;
818 int count2;
819 sopno pos;
820 bool handled;
821 int i;
822 wint_t wc;
823 sopno subno;
824 # define BACKSL (1<<CHAR_BIT)
825
826 pos = HERE(); /* repetition op, if any, covers from here */
827 handled = false;
828
829 assert(MORE()); /* caller should have ensured this */
830 c = (uch)GETNEXT();
831 if (c == '\\') {
832 (void)REQUIRE(MORE(), REG_EESCAPE);
833 cc = (uch)GETNEXT();
834 c = BACKSL | cc;
835 #ifdef LIBREGEX
836 if (p->gnuext) {
837 handled = true;
838 switch (c) {
839 case BACKSL|'`':
840 EMIT(OBOS, 0);
841 break;
842 case BACKSL|'\'':
843 EMIT(OEOS, 0);
844 break;
845 case BACKSL|'B':
846 EMIT(ONWBND, 0);
847 break;
848 case BACKSL|'b':
849 EMIT(OWBND, 0);
850 break;
851 case BACKSL|'W':
852 case BACKSL|'w':
853 case BACKSL|'S':
854 case BACKSL|'s':
855 p_b_pseudoclass(p, cc);
856 break;
857 default:
858 handled = false;
859 }
860 }
861 #endif
862 }
863 if (!handled) {
864 switch (c) {
865 case '.':
866 if (p->g->cflags®_NEWLINE)
867 nonnewline(p);
868 else
869 EMIT(OANY, 0);
870 break;
871 case '[':
872 p_bracket(p);
873 break;
874 case BACKSL|'<':
875 EMIT(OBOW, 0);
876 break;
877 case BACKSL|'>':
878 EMIT(OEOW, 0);
879 break;
880 case BACKSL|'{':
881 SETERROR(REG_BADRPT);
882 break;
883 case BACKSL|'(':
884 p->g->nsub++;
885 subno = p->g->nsub;
886 if (subno < NPAREN)
887 p->pbegin[subno] = HERE();
888 EMIT(OLPAREN, subno);
889 /* the MORE here is an error heuristic */
890 if (MORE() && !SEETWO('\\', ')'))
891 p_re(p, '\\', ')');
892 if (subno < NPAREN) {
893 p->pend[subno] = HERE();
894 assert(p->pend[subno] != 0);
895 }
896 EMIT(ORPAREN, subno);
897 (void)REQUIRE(EATTWO('\\', ')'), REG_EPAREN);
898 break;
899 case BACKSL|')': /* should not get here -- must be user */
900 SETERROR(REG_EPAREN);
901 break;
902 case BACKSL|'1':
903 case BACKSL|'2':
904 case BACKSL|'3':
905 case BACKSL|'4':
906 case BACKSL|'5':
907 case BACKSL|'6':
908 case BACKSL|'7':
909 case BACKSL|'8':
910 case BACKSL|'9':
911 i = (c&~BACKSL) - '0';
912 assert(i < NPAREN);
913 if (p->pend[i] != 0) {
914 assert(i <= p->g->nsub);
915 EMIT(OBACK_, i);
916 assert(p->pbegin[i] != 0);
917 assert(OP(p->strip[p->pbegin[i]]) == OLPAREN);
918 assert(OP(p->strip[p->pend[i]]) == ORPAREN);
919 (void) dupl(p, p->pbegin[i]+1, p->pend[i]);
920 EMIT(O_BACK, i);
921 } else
922 SETERROR(REG_ESUBREG);
923 p->g->backrefs = 1;
924 break;
925 case '*':
926 /*
927 * Ordinary if used as the first character beyond BOL anchor of
928 * a (sub-)expression, counts as a bad repetition operator if it
929 * appears otherwise.
930 */
931 (void)REQUIRE(bc->nchain == 0, REG_BADRPT);
932 /* FALLTHROUGH */
933 default:
934 if (p->error != 0)
935 return (false); /* Definitely not $... */
936 p->next--;
937 wc = WGETNEXT();
938 if ((c & BACKSL) == 0 || may_escape(p, wc))
939 ordinary(p, wc);
940 else
941 SETERROR(REG_EESCAPE);
942 break;
943 }
944 }
945
946 if (EAT('*')) { /* implemented as +? */
947 /* this case does not require the (y|) trick, noKLUDGE */
948 INSERT(OPLUS_, pos);
949 ASTERN(O_PLUS, pos);
950 INSERT(OQUEST_, pos);
951 ASTERN(O_QUEST, pos);
952 #ifdef LIBREGEX
953 } else if (p->gnuext && EATTWO('\\', '?')) {
954 INSERT(OQUEST_, pos);
955 ASTERN(O_QUEST, pos);
956 } else if (p->gnuext && EATTWO('\\', '+')) {
957 INSERT(OPLUS_, pos);
958 ASTERN(O_PLUS, pos);
959 #endif
960 } else if (EATTWO('\\', '{')) {
961 count = p_count(p);
962 if (EAT(',')) {
963 if (MORE() && isdigit((uch)PEEK())) {
964 count2 = p_count(p);
965 (void)REQUIRE(count <= count2, REG_BADBR);
966 } else /* single number with comma */
967 count2 = INFINITY;
968 } else /* just a single number */
969 count2 = count;
970 repeat(p, pos, count, count2);
971 if (!EATTWO('\\', '}')) { /* error heuristics */
972 while (MORE() && !SEETWO('\\', '}'))
973 NEXT();
974 (void)REQUIRE(MORE(), REG_EBRACE);
975 SETERROR(REG_BADBR);
976 }
977 } else if (c == '$') /* $ (but not \$) ends it */
978 return (true);
979
980 return (false);
981 }
982
983 /*
984 - p_count - parse a repetition count
985 == static int p_count(struct parse *p);
986 */
987 static int /* the value */
p_count(struct parse * p)988 p_count(struct parse *p)
989 {
990 int count = 0;
991 int ndigits = 0;
992
993 while (MORE() && isdigit((uch)PEEK()) && count <= DUPMAX) {
994 count = count*10 + ((uch)GETNEXT() - '0');
995 ndigits++;
996 }
997
998 (void)REQUIRE(ndigits > 0 && count <= DUPMAX, REG_BADBR);
999 return(count);
1000 }
1001
1002 /*
1003 - p_bracket - parse a bracketed character list
1004 == static void p_bracket(struct parse *p);
1005 */
1006 static void
p_bracket(struct parse * p)1007 p_bracket(struct parse *p)
1008 {
1009 cset *cs;
1010 wint_t ch;
1011
1012 /* Dept of Truly Sickening Special-Case Kludges */
1013 if (p->end - p->next > 5) {
1014 if (strncmp(p->next, "[:<:]]", 6) == 0) {
1015 EMIT(OBOW, 0);
1016 NEXTn(6);
1017 return;
1018 }
1019 if (strncmp(p->next, "[:>:]]", 6) == 0) {
1020 EMIT(OEOW, 0);
1021 NEXTn(6);
1022 return;
1023 }
1024 }
1025
1026 if ((cs = allocset(p)) == NULL)
1027 return;
1028
1029 if (p->g->cflags®_ICASE)
1030 cs->icase = 1;
1031 if (EAT('^'))
1032 cs->invert = 1;
1033 if (EAT(']'))
1034 CHadd(p, cs, ']');
1035 else if (EAT('-'))
1036 CHadd(p, cs, '-');
1037 while (MORE() && PEEK() != ']' && !SEETWO('-', ']'))
1038 p_b_term(p, cs);
1039 if (EAT('-'))
1040 CHadd(p, cs, '-');
1041 (void)MUSTEAT(']', REG_EBRACK);
1042
1043 if (p->error != 0) /* don't mess things up further */
1044 return;
1045
1046 if (cs->invert && p->g->cflags®_NEWLINE)
1047 cs->bmp['\n' >> 3] |= 1 << ('\n' & 7);
1048
1049 if ((ch = singleton(cs)) != OUT) { /* optimize singleton sets */
1050 ordinary(p, ch);
1051 freeset(p, cs);
1052 } else
1053 EMIT(OANYOF, (int)(cs - p->g->sets));
1054 }
1055
1056 static int
p_range_cmp(wchar_t c1,wchar_t c2)1057 p_range_cmp(wchar_t c1, wchar_t c2)
1058 {
1059 #ifndef LIBREGEX
1060 return __wcollate_range_cmp(c1, c2);
1061 #else
1062 /* Copied from libc/collate __wcollate_range_cmp */
1063 wchar_t s1[2], s2[2];
1064
1065 s1[0] = c1;
1066 s1[1] = L'\0';
1067 s2[0] = c2;
1068 s2[1] = L'\0';
1069 return (wcscoll(s1, s2));
1070 #endif
1071 }
1072
1073 /*
1074 - p_b_term - parse one term of a bracketed character list
1075 == static void p_b_term(struct parse *p, cset *cs);
1076 */
1077 static void
p_b_term(struct parse * p,cset * cs)1078 p_b_term(struct parse *p, cset *cs)
1079 {
1080 char c;
1081 wint_t start, finish;
1082 wint_t i;
1083 #ifndef LIBREGEX
1084 struct xlocale_collate *table =
1085 (struct xlocale_collate*)__get_locale()->components[XLC_COLLATE];
1086 #endif
1087 /* classify what we've got */
1088 switch ((MORE()) ? PEEK() : '\0') {
1089 case '[':
1090 c = (MORE2()) ? PEEK2() : '\0';
1091 break;
1092 case '-':
1093 SETERROR(REG_ERANGE);
1094 return; /* NOTE RETURN */
1095 default:
1096 c = '\0';
1097 break;
1098 }
1099
1100 switch (c) {
1101 case ':': /* character class */
1102 NEXT2();
1103 (void)REQUIRE(MORE(), REG_EBRACK);
1104 c = PEEK();
1105 (void)REQUIRE(c != '-' && c != ']', REG_ECTYPE);
1106 p_b_cclass(p, cs);
1107 (void)REQUIRE(MORE(), REG_EBRACK);
1108 (void)REQUIRE(EATTWO(':', ']'), REG_ECTYPE);
1109 break;
1110 case '=': /* equivalence class */
1111 NEXT2();
1112 (void)REQUIRE(MORE(), REG_EBRACK);
1113 c = PEEK();
1114 (void)REQUIRE(c != '-' && c != ']', REG_ECOLLATE);
1115 p_b_eclass(p, cs);
1116 (void)REQUIRE(MORE(), REG_EBRACK);
1117 (void)REQUIRE(EATTWO('=', ']'), REG_ECOLLATE);
1118 break;
1119 default: /* symbol, ordinary character, or range */
1120 start = p_b_symbol(p);
1121 if (SEE('-') && MORE2() && PEEK2() != ']') {
1122 /* range */
1123 NEXT();
1124 if (EAT('-'))
1125 finish = '-';
1126 else
1127 finish = p_b_symbol(p);
1128 } else
1129 finish = start;
1130 if (start == finish)
1131 CHadd(p, cs, start);
1132 else {
1133 #ifndef LIBREGEX
1134 if (table->__collate_load_error || MB_CUR_MAX > 1) {
1135 #else
1136 if (MB_CUR_MAX > 1) {
1137 #endif
1138 (void)REQUIRE(start <= finish, REG_ERANGE);
1139 CHaddrange(p, cs, start, finish);
1140 } else {
1141 (void)REQUIRE(p_range_cmp(start, finish) <= 0, REG_ERANGE);
1142 for (i = 0; i <= UCHAR_MAX; i++) {
1143 if (p_range_cmp(start, i) <= 0 &&
1144 p_range_cmp(i, finish) <= 0 )
1145 CHadd(p, cs, i);
1146 }
1147 }
1148 }
1149 break;
1150 }
1151 }
1152
1153 /*
1154 - p_b_pseudoclass - parse a pseudo-class (\w, \W, \s, \S)
1155 == static int p_b_pseudoclass(struct parse *p, char c)
1156 */
1157 static int
1158 p_b_pseudoclass(struct parse *p, char c) {
1159 cset *cs;
1160
1161 if ((cs = allocset(p)) == NULL)
1162 return(0);
1163
1164 if (p->g->cflags®_ICASE)
1165 cs->icase = 1;
1166
1167 switch (c) {
1168 case 'W':
1169 cs->invert = 1;
1170 /* PASSTHROUGH */
1171 case 'w':
1172 p_b_cclass_named(p, cs, "alnum");
1173 break;
1174 case 'S':
1175 cs->invert = 1;
1176 /* PASSTHROUGH */
1177 case 's':
1178 p_b_cclass_named(p, cs, "space");
1179 break;
1180 default:
1181 return(0);
1182 }
1183
1184 EMIT(OANYOF, (int)(cs - p->g->sets));
1185 return(1);
1186 }
1187
1188 /*
1189 - p_b_cclass - parse a character-class name and deal with it
1190 == static void p_b_cclass(struct parse *p, cset *cs);
1191 */
1192 static void
1193 p_b_cclass(struct parse *p, cset *cs)
1194 {
1195 const char *sp = p->next;
1196 size_t len;
1197 char clname[16];
1198
1199 while (MORE() && isalpha((uch)PEEK()))
1200 NEXT();
1201 len = p->next - sp;
1202 if (len >= sizeof(clname) - 1) {
1203 SETERROR(REG_ECTYPE);
1204 return;
1205 }
1206 memcpy(clname, sp, len);
1207 clname[len] = '\0';
1208
1209 p_b_cclass_named(p, cs, clname);
1210 }
1211 /*
1212 - p_b_cclass_named - deal with a named character class
1213 == static void p_b_cclass_named(struct parse *p, cset *cs, const char []);
1214 */
1215 static void
1216 p_b_cclass_named(struct parse *p, cset *cs, const char clname[]) {
1217 wctype_t wct;
1218
1219 if ((wct = wctype(clname)) == 0) {
1220 SETERROR(REG_ECTYPE);
1221 return;
1222 }
1223 CHaddtype(p, cs, wct);
1224 }
1225
1226 /*
1227 - p_b_eclass - parse an equivalence-class name and deal with it
1228 == static void p_b_eclass(struct parse *p, cset *cs);
1229 *
1230 * This implementation is incomplete. xxx
1231 */
1232 static void
1233 p_b_eclass(struct parse *p, cset *cs)
1234 {
1235 wint_t c;
1236
1237 c = p_b_coll_elem(p, '=');
1238 CHadd(p, cs, c);
1239 }
1240
1241 /*
1242 - p_b_symbol - parse a character or [..]ed multicharacter collating symbol
1243 == static wint_t p_b_symbol(struct parse *p);
1244 */
1245 static wint_t /* value of symbol */
1246 p_b_symbol(struct parse *p)
1247 {
1248 wint_t value;
1249
1250 (void)REQUIRE(MORE(), REG_EBRACK);
1251 if (!EATTWO('[', '.'))
1252 return(WGETNEXT());
1253
1254 /* collating symbol */
1255 value = p_b_coll_elem(p, '.');
1256 (void)REQUIRE(EATTWO('.', ']'), REG_ECOLLATE);
1257 return(value);
1258 }
1259
1260 /*
1261 - p_b_coll_elem - parse a collating-element name and look it up
1262 == static wint_t p_b_coll_elem(struct parse *p, wint_t endc);
1263 */
1264 static wint_t /* value of collating element */
1265 p_b_coll_elem(struct parse *p,
1266 wint_t endc) /* name ended by endc,']' */
1267 {
1268 const char *sp = p->next;
1269 struct cname *cp;
1270 mbstate_t mbs;
1271 wchar_t wc;
1272 size_t clen, len;
1273
1274 while (MORE() && !SEETWO(endc, ']'))
1275 NEXT();
1276 if (!MORE()) {
1277 SETERROR(REG_EBRACK);
1278 return(0);
1279 }
1280 len = p->next - sp;
1281 for (cp = cnames; cp->name != NULL; cp++)
1282 if (strncmp(cp->name, sp, len) == 0 && strlen(cp->name) == len)
1283 return(cp->code); /* known name */
1284 memset(&mbs, 0, sizeof(mbs));
1285 if ((clen = mbrtowc(&wc, sp, len, &mbs)) == len)
1286 return (wc); /* single character */
1287 else if (clen == (size_t)-1 || clen == (size_t)-2)
1288 SETERROR(REG_ILLSEQ);
1289 else
1290 SETERROR(REG_ECOLLATE); /* neither */
1291 return(0);
1292 }
1293
1294 /*
1295 - may_escape - determine whether 'ch' is escape-able in the current context
1296 == static int may_escape(struct parse *p, const wint_t ch)
1297 */
1298 static bool
1299 may_escape(struct parse *p, const wint_t ch)
1300 {
1301
1302 if ((p->pflags & PFLAG_LEGACY_ESC) != 0)
1303 return (true);
1304 if (iswalpha(ch) || ch == '\'' || ch == '`')
1305 return (false);
1306 return (true);
1307 #ifdef NOTYET
1308 /*
1309 * Build a whitelist of characters that may be escaped to produce an
1310 * ordinary in the current context. This assumes that these have not
1311 * been otherwise interpreted as a special character. Escaping an
1312 * ordinary character yields undefined results according to
1313 * IEEE 1003.1-2008. Some extensions (notably, some GNU extensions) take
1314 * advantage of this and use escaped ordinary characters to provide
1315 * special meaning, e.g. \b, \B, \w, \W, \s, \S.
1316 */
1317 switch(ch) {
1318 case '|':
1319 case '+':
1320 case '?':
1321 /* The above characters may not be escaped in BREs */
1322 if (!(p->g->cflags®_EXTENDED))
1323 return (false);
1324 /* Fallthrough */
1325 case '(':
1326 case ')':
1327 case '{':
1328 case '}':
1329 case '.':
1330 case '[':
1331 case ']':
1332 case '\\':
1333 case '*':
1334 case '^':
1335 case '$':
1336 return (true);
1337 default:
1338 return (false);
1339 }
1340 #endif
1341 }
1342
1343 /*
1344 - othercase - return the case counterpart of an alphabetic
1345 == static wint_t othercase(wint_t ch);
1346 */
1347 static wint_t /* if no counterpart, return ch */
1348 othercase(wint_t ch)
1349 {
1350 assert(iswalpha(ch));
1351 if (iswupper(ch))
1352 return(towlower(ch));
1353 else if (iswlower(ch))
1354 return(towupper(ch));
1355 else /* peculiar, but could happen */
1356 return(ch);
1357 }
1358
1359 /*
1360 - bothcases - emit a dualcase version of a two-case character
1361 == static void bothcases(struct parse *p, wint_t ch);
1362 *
1363 * Boy, is this implementation ever a kludge...
1364 */
1365 static void
1366 bothcases(struct parse *p, wint_t ch)
1367 {
1368 const char *oldnext = p->next;
1369 const char *oldend = p->end;
1370 char bracket[3 + MB_LEN_MAX];
1371 size_t n;
1372 mbstate_t mbs;
1373
1374 assert(othercase(ch) != ch); /* p_bracket() would recurse */
1375 p->next = bracket;
1376 memset(&mbs, 0, sizeof(mbs));
1377 n = wcrtomb(bracket, ch, &mbs);
1378 assert(n != (size_t)-1);
1379 bracket[n] = ']';
1380 bracket[n + 1] = '\0';
1381 p->end = bracket+n+1;
1382 p_bracket(p);
1383 assert(p->next == p->end);
1384 p->next = oldnext;
1385 p->end = oldend;
1386 }
1387
1388 /*
1389 - ordinary - emit an ordinary character
1390 == static void ordinary(struct parse *p, wint_t ch);
1391 */
1392 static void
1393 ordinary(struct parse *p, wint_t ch)
1394 {
1395 cset *cs;
1396
1397 if ((p->g->cflags®_ICASE) && iswalpha(ch) && othercase(ch) != ch)
1398 bothcases(p, ch);
1399 else if ((ch & OPDMASK) == ch)
1400 EMIT(OCHAR, ch);
1401 else {
1402 /*
1403 * Kludge: character is too big to fit into an OCHAR operand.
1404 * Emit a singleton set.
1405 */
1406 if ((cs = allocset(p)) == NULL)
1407 return;
1408 CHadd(p, cs, ch);
1409 EMIT(OANYOF, (int)(cs - p->g->sets));
1410 }
1411 }
1412
1413 /*
1414 - nonnewline - emit REG_NEWLINE version of OANY
1415 == static void nonnewline(struct parse *p);
1416 *
1417 * Boy, is this implementation ever a kludge...
1418 */
1419 static void
1420 nonnewline(struct parse *p)
1421 {
1422 const char *oldnext = p->next;
1423 const char *oldend = p->end;
1424 char bracket[4];
1425
1426 p->next = bracket;
1427 p->end = bracket+3;
1428 bracket[0] = '^';
1429 bracket[1] = '\n';
1430 bracket[2] = ']';
1431 bracket[3] = '\0';
1432 p_bracket(p);
1433 assert(p->next == bracket+3);
1434 p->next = oldnext;
1435 p->end = oldend;
1436 }
1437
1438 /*
1439 - repeat - generate code for a bounded repetition, recursively if needed
1440 == static void repeat(struct parse *p, sopno start, int from, int to);
1441 */
1442 static void
1443 repeat(struct parse *p,
1444 sopno start, /* operand from here to end of strip */
1445 int from, /* repeated from this number */
1446 int to) /* to this number of times (maybe INFINITY) */
1447 {
1448 sopno finish = HERE();
1449 # define N 2
1450 # define INF 3
1451 # define REP(f, t) ((f)*8 + (t))
1452 # define MAP(n) (((n) <= 1) ? (n) : ((n) == INFINITY) ? INF : N)
1453 sopno copy;
1454
1455 if (p->error != 0) /* head off possible runaway recursion */
1456 return;
1457
1458 assert(from <= to);
1459
1460 switch (REP(MAP(from), MAP(to))) {
1461 case REP(0, 0): /* must be user doing this */
1462 DROP(finish-start); /* drop the operand */
1463 break;
1464 case REP(0, 1): /* as x{1,1}? */
1465 case REP(0, N): /* as x{1,n}? */
1466 case REP(0, INF): /* as x{1,}? */
1467 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
1468 INSERT(OCH_, start); /* offset is wrong... */
1469 repeat(p, start+1, 1, to);
1470 ASTERN(OOR1, start);
1471 AHEAD(start); /* ... fix it */
1472 EMIT(OOR2, 0);
1473 AHEAD(THERE());
1474 ASTERN(O_CH, THERETHERE());
1475 break;
1476 case REP(1, 1): /* trivial case */
1477 /* done */
1478 break;
1479 case REP(1, N): /* as x?x{1,n-1} */
1480 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
1481 INSERT(OCH_, start);
1482 ASTERN(OOR1, start);
1483 AHEAD(start);
1484 EMIT(OOR2, 0); /* offset very wrong... */
1485 AHEAD(THERE()); /* ...so fix it */
1486 ASTERN(O_CH, THERETHERE());
1487 copy = dupl(p, start+1, finish+1);
1488 assert(copy == finish+4);
1489 repeat(p, copy, 1, to-1);
1490 break;
1491 case REP(1, INF): /* as x+ */
1492 INSERT(OPLUS_, start);
1493 ASTERN(O_PLUS, start);
1494 break;
1495 case REP(N, N): /* as xx{m-1,n-1} */
1496 copy = dupl(p, start, finish);
1497 repeat(p, copy, from-1, to-1);
1498 break;
1499 case REP(N, INF): /* as xx{n-1,INF} */
1500 copy = dupl(p, start, finish);
1501 repeat(p, copy, from-1, to);
1502 break;
1503 default: /* "can't happen" */
1504 SETERROR(REG_ASSERT); /* just in case */
1505 break;
1506 }
1507 }
1508
1509 /*
1510 - wgetnext - helper function for WGETNEXT() macro. Gets the next wide
1511 - character from the parse struct, signals a REG_ILLSEQ error if the
1512 - character can't be converted. Returns the number of bytes consumed.
1513 */
1514 static wint_t
1515 wgetnext(struct parse *p)
1516 {
1517 mbstate_t mbs;
1518 wchar_t wc;
1519 size_t n;
1520
1521 memset(&mbs, 0, sizeof(mbs));
1522 n = mbrtowc(&wc, p->next, p->end - p->next, &mbs);
1523 if (n == (size_t)-1 || n == (size_t)-2) {
1524 SETERROR(REG_ILLSEQ);
1525 return (0);
1526 }
1527 if (n == 0)
1528 n = 1;
1529 p->next += n;
1530 return (wc);
1531 }
1532
1533 /*
1534 - seterr - set an error condition
1535 == static int seterr(struct parse *p, int e);
1536 */
1537 static int /* useless but makes type checking happy */
1538 seterr(struct parse *p, int e)
1539 {
1540 if (p->error == 0) /* keep earliest error condition */
1541 p->error = e;
1542 p->next = nuls; /* try to bring things to a halt */
1543 p->end = nuls;
1544 return(0); /* make the return value well-defined */
1545 }
1546
1547 /*
1548 - allocset - allocate a set of characters for []
1549 == static cset *allocset(struct parse *p);
1550 */
1551 static cset *
1552 allocset(struct parse *p)
1553 {
1554 cset *cs, *ncs;
1555
1556 ncs = reallocarray(p->g->sets, p->g->ncsets + 1, sizeof(*ncs));
1557 if (ncs == NULL) {
1558 SETERROR(REG_ESPACE);
1559 return (NULL);
1560 }
1561 p->g->sets = ncs;
1562 cs = &p->g->sets[p->g->ncsets++];
1563 memset(cs, 0, sizeof(*cs));
1564
1565 return(cs);
1566 }
1567
1568 /*
1569 - freeset - free a now-unused set
1570 == static void freeset(struct parse *p, cset *cs);
1571 */
1572 static void
1573 freeset(struct parse *p, cset *cs)
1574 {
1575 cset *top = &p->g->sets[p->g->ncsets];
1576
1577 free(cs->wides);
1578 free(cs->ranges);
1579 free(cs->types);
1580 memset(cs, 0, sizeof(*cs));
1581 if (cs == top-1) /* recover only the easy case */
1582 p->g->ncsets--;
1583 }
1584
1585 /*
1586 - singleton - Determine whether a set contains only one character,
1587 - returning it if so, otherwise returning OUT.
1588 */
1589 static wint_t
1590 singleton(cset *cs)
1591 {
1592 wint_t i, s, n;
1593
1594 /* Exclude the complicated cases we don't want to deal with */
1595 if (cs->nranges != 0 || cs->ntypes != 0 || cs->icase != 0)
1596 return (OUT);
1597
1598 if (cs->nwides > 1)
1599 return (OUT);
1600
1601 /* Count the number of characters present in the bitmap */
1602 for (i = n = 0; i < NC; i++)
1603 if (CHIN(cs, i)) {
1604 n++;
1605 s = i;
1606 }
1607
1608 if (n > 1)
1609 return (OUT);
1610
1611 if (n == 1) {
1612 if (cs->nwides == 0)
1613 return (s);
1614 else
1615 return (OUT);
1616 }
1617 if (cs->nwides == 1)
1618 return (cs->wides[0]);
1619
1620 return (OUT);
1621 }
1622
1623 /*
1624 - CHadd - add character to character set.
1625 */
1626 static void
1627 CHadd(struct parse *p, cset *cs, wint_t ch)
1628 {
1629 wint_t nch, *newwides;
1630 assert(ch >= 0);
1631 if (ch < NC)
1632 cs->bmp[ch >> 3] |= 1 << (ch & 7);
1633 else {
1634 newwides = reallocarray(cs->wides, cs->nwides + 1,
1635 sizeof(*cs->wides));
1636 if (newwides == NULL) {
1637 SETERROR(REG_ESPACE);
1638 return;
1639 }
1640 cs->wides = newwides;
1641 cs->wides[cs->nwides++] = ch;
1642 }
1643 if (cs->icase) {
1644 if ((nch = towlower(ch)) < NC)
1645 cs->bmp[nch >> 3] |= 1 << (nch & 7);
1646 if ((nch = towupper(ch)) < NC)
1647 cs->bmp[nch >> 3] |= 1 << (nch & 7);
1648 }
1649 }
1650
1651 /*
1652 - CHaddrange - add all characters in the range [min,max] to a character set.
1653 */
1654 static void
1655 CHaddrange(struct parse *p, cset *cs, wint_t min, wint_t max)
1656 {
1657 crange *newranges;
1658
1659 for (; min < NC && min <= max; min++)
1660 CHadd(p, cs, min);
1661 if (min >= max)
1662 return;
1663 newranges = reallocarray(cs->ranges, cs->nranges + 1,
1664 sizeof(*cs->ranges));
1665 if (newranges == NULL) {
1666 SETERROR(REG_ESPACE);
1667 return;
1668 }
1669 cs->ranges = newranges;
1670 cs->ranges[cs->nranges].min = min;
1671 cs->ranges[cs->nranges].max = max;
1672 cs->nranges++;
1673 }
1674
1675 /*
1676 - CHaddtype - add all characters of a certain type to a character set.
1677 */
1678 static void
1679 CHaddtype(struct parse *p, cset *cs, wctype_t wct)
1680 {
1681 wint_t i;
1682 wctype_t *newtypes;
1683
1684 for (i = 0; i < NC; i++)
1685 if (iswctype(i, wct))
1686 CHadd(p, cs, i);
1687 newtypes = reallocarray(cs->types, cs->ntypes + 1,
1688 sizeof(*cs->types));
1689 if (newtypes == NULL) {
1690 SETERROR(REG_ESPACE);
1691 return;
1692 }
1693 cs->types = newtypes;
1694 cs->types[cs->ntypes++] = wct;
1695 }
1696
1697 /*
1698 - dupl - emit a duplicate of a bunch of sops
1699 == static sopno dupl(struct parse *p, sopno start, sopno finish);
1700 */
1701 static sopno /* start of duplicate */
1702 dupl(struct parse *p,
1703 sopno start, /* from here */
1704 sopno finish) /* to this less one */
1705 {
1706 sopno ret = HERE();
1707 sopno len = finish - start;
1708
1709 assert(finish >= start);
1710 if (len == 0)
1711 return(ret);
1712 if (!enlarge(p, p->ssize + len)) /* this many unexpected additions */
1713 return(ret);
1714 (void) memcpy((char *)(p->strip + p->slen),
1715 (char *)(p->strip + start), (size_t)len*sizeof(sop));
1716 p->slen += len;
1717 return(ret);
1718 }
1719
1720 /*
1721 - doemit - emit a strip operator
1722 == static void doemit(struct parse *p, sop op, size_t opnd);
1723 *
1724 * It might seem better to implement this as a macro with a function as
1725 * hard-case backup, but it's just too big and messy unless there are
1726 * some changes to the data structures. Maybe later.
1727 */
1728 static void
1729 doemit(struct parse *p, sop op, size_t opnd)
1730 {
1731 /* avoid making error situations worse */
1732 if (p->error != 0)
1733 return;
1734
1735 /* deal with oversize operands ("can't happen", more or less) */
1736 assert(opnd < 1<<OPSHIFT);
1737
1738 /* deal with undersized strip */
1739 if (p->slen >= p->ssize)
1740 if (!enlarge(p, (p->ssize+1) / 2 * 3)) /* +50% */
1741 return;
1742
1743 /* finally, it's all reduced to the easy case */
1744 p->strip[p->slen++] = SOP(op, opnd);
1745 }
1746
1747 /*
1748 - doinsert - insert a sop into the strip
1749 == static void doinsert(struct parse *p, sop op, size_t opnd, sopno pos);
1750 */
1751 static void
1752 doinsert(struct parse *p, sop op, size_t opnd, sopno pos)
1753 {
1754 sopno sn;
1755 sop s;
1756 int i;
1757
1758 /* avoid making error situations worse */
1759 if (p->error != 0)
1760 return;
1761
1762 sn = HERE();
1763 EMIT(op, opnd); /* do checks, ensure space */
1764 assert(HERE() == sn+1);
1765 s = p->strip[sn];
1766
1767 /* adjust paren pointers */
1768 assert(pos > 0);
1769 for (i = 1; i < NPAREN; i++) {
1770 if (p->pbegin[i] >= pos) {
1771 p->pbegin[i]++;
1772 }
1773 if (p->pend[i] >= pos) {
1774 p->pend[i]++;
1775 }
1776 }
1777
1778 memmove((char *)&p->strip[pos+1], (char *)&p->strip[pos],
1779 (HERE()-pos-1)*sizeof(sop));
1780 p->strip[pos] = s;
1781 }
1782
1783 /*
1784 - dofwd - complete a forward reference
1785 == static void dofwd(struct parse *p, sopno pos, sop value);
1786 */
1787 static void
1788 dofwd(struct parse *p, sopno pos, sop value)
1789 {
1790 /* avoid making error situations worse */
1791 if (p->error != 0)
1792 return;
1793
1794 assert(value < 1<<OPSHIFT);
1795 p->strip[pos] = OP(p->strip[pos]) | value;
1796 }
1797
1798 /*
1799 - enlarge - enlarge the strip
1800 == static int enlarge(struct parse *p, sopno size);
1801 */
1802 static int
1803 enlarge(struct parse *p, sopno size)
1804 {
1805 sop *sp;
1806
1807 if (p->ssize >= size)
1808 return 1;
1809
1810 sp = reallocarray(p->strip, size, sizeof(sop));
1811 if (sp == NULL) {
1812 SETERROR(REG_ESPACE);
1813 return 0;
1814 }
1815 p->strip = sp;
1816 p->ssize = size;
1817 return 1;
1818 }
1819
1820 /*
1821 - stripsnug - compact the strip
1822 == static void stripsnug(struct parse *p, struct re_guts *g);
1823 */
1824 static void
1825 stripsnug(struct parse *p, struct re_guts *g)
1826 {
1827 g->nstates = p->slen;
1828 g->strip = reallocarray((char *)p->strip, p->slen, sizeof(sop));
1829 if (g->strip == NULL) {
1830 SETERROR(REG_ESPACE);
1831 g->strip = p->strip;
1832 }
1833 }
1834
1835 /*
1836 - findmust - fill in must and mlen with longest mandatory literal string
1837 == static void findmust(struct parse *p, struct re_guts *g);
1838 *
1839 * This algorithm could do fancy things like analyzing the operands of |
1840 * for common subsequences. Someday. This code is simple and finds most
1841 * of the interesting cases.
1842 *
1843 * Note that must and mlen got initialized during setup.
1844 */
1845 static void
1846 findmust(struct parse *p, struct re_guts *g)
1847 {
1848 sop *scan;
1849 sop *start = NULL;
1850 sop *newstart = NULL;
1851 sopno newlen;
1852 sop s;
1853 char *cp;
1854 int offset;
1855 char buf[MB_LEN_MAX];
1856 size_t clen;
1857 mbstate_t mbs;
1858
1859 /* avoid making error situations worse */
1860 if (p->error != 0)
1861 return;
1862
1863 /*
1864 * It's not generally safe to do a ``char'' substring search on
1865 * multibyte character strings, but it's safe for at least
1866 * UTF-8 (see RFC 3629).
1867 */
1868 if (MB_CUR_MAX > 1 &&
1869 strcmp(_CurrentRuneLocale->__encoding, "UTF-8") != 0)
1870 return;
1871
1872 /* find the longest OCHAR sequence in strip */
1873 newlen = 0;
1874 offset = 0;
1875 g->moffset = 0;
1876 scan = g->strip + 1;
1877 do {
1878 s = *scan++;
1879 switch (OP(s)) {
1880 case OCHAR: /* sequence member */
1881 if (newlen == 0) { /* new sequence */
1882 memset(&mbs, 0, sizeof(mbs));
1883 newstart = scan - 1;
1884 }
1885 clen = wcrtomb(buf, OPND(s), &mbs);
1886 if (clen == (size_t)-1)
1887 goto toohard;
1888 newlen += clen;
1889 break;
1890 case OPLUS_: /* things that don't break one */
1891 case OLPAREN:
1892 case ORPAREN:
1893 break;
1894 case OQUEST_: /* things that must be skipped */
1895 case OCH_:
1896 offset = altoffset(scan, offset);
1897 scan--;
1898 do {
1899 scan += OPND(s);
1900 s = *scan;
1901 /* assert() interferes w debug printouts */
1902 if (OP(s) != (sop)O_QUEST &&
1903 OP(s) != (sop)O_CH && OP(s) != (sop)OOR2) {
1904 g->iflags |= BAD;
1905 return;
1906 }
1907 } while (OP(s) != (sop)O_QUEST && OP(s) != (sop)O_CH);
1908 /* FALLTHROUGH */
1909 case OBOW: /* things that break a sequence */
1910 case OEOW:
1911 case OBOL:
1912 case OEOL:
1913 case OBOS:
1914 case OEOS:
1915 case OWBND:
1916 case ONWBND:
1917 case O_QUEST:
1918 case O_CH:
1919 case OEND:
1920 if (newlen > (sopno)g->mlen) { /* ends one */
1921 start = newstart;
1922 g->mlen = newlen;
1923 if (offset > -1) {
1924 g->moffset += offset;
1925 offset = newlen;
1926 } else
1927 g->moffset = offset;
1928 } else {
1929 if (offset > -1)
1930 offset += newlen;
1931 }
1932 newlen = 0;
1933 break;
1934 case OANY:
1935 if (newlen > (sopno)g->mlen) { /* ends one */
1936 start = newstart;
1937 g->mlen = newlen;
1938 if (offset > -1) {
1939 g->moffset += offset;
1940 offset = newlen;
1941 } else
1942 g->moffset = offset;
1943 } else {
1944 if (offset > -1)
1945 offset += newlen;
1946 }
1947 if (offset > -1)
1948 offset++;
1949 newlen = 0;
1950 break;
1951 case OANYOF: /* may or may not invalidate offset */
1952 /* First, everything as OANY */
1953 if (newlen > (sopno)g->mlen) { /* ends one */
1954 start = newstart;
1955 g->mlen = newlen;
1956 if (offset > -1) {
1957 g->moffset += offset;
1958 offset = newlen;
1959 } else
1960 g->moffset = offset;
1961 } else {
1962 if (offset > -1)
1963 offset += newlen;
1964 }
1965 if (offset > -1)
1966 offset++;
1967 newlen = 0;
1968 break;
1969 toohard:
1970 default:
1971 /* Anything here makes it impossible or too hard
1972 * to calculate the offset -- so we give up;
1973 * save the last known good offset, in case the
1974 * must sequence doesn't occur later.
1975 */
1976 if (newlen > (sopno)g->mlen) { /* ends one */
1977 start = newstart;
1978 g->mlen = newlen;
1979 if (offset > -1)
1980 g->moffset += offset;
1981 else
1982 g->moffset = offset;
1983 }
1984 offset = -1;
1985 newlen = 0;
1986 break;
1987 }
1988 } while (OP(s) != OEND);
1989
1990 if (g->mlen == 0) { /* there isn't one */
1991 g->moffset = -1;
1992 return;
1993 }
1994
1995 /* turn it into a character string */
1996 g->must = malloc((size_t)g->mlen + 1);
1997 if (g->must == NULL) { /* argh; just forget it */
1998 g->mlen = 0;
1999 g->moffset = -1;
2000 return;
2001 }
2002 cp = g->must;
2003 scan = start;
2004 memset(&mbs, 0, sizeof(mbs));
2005 while (cp < g->must + g->mlen) {
2006 while (OP(s = *scan++) != OCHAR)
2007 continue;
2008 clen = wcrtomb(cp, OPND(s), &mbs);
2009 assert(clen != (size_t)-1);
2010 cp += clen;
2011 }
2012 assert(cp == g->must + g->mlen);
2013 *cp++ = '\0'; /* just on general principles */
2014 }
2015
2016 /*
2017 - altoffset - choose biggest offset among multiple choices
2018 == static int altoffset(sop *scan, int offset);
2019 *
2020 * Compute, recursively if necessary, the largest offset among multiple
2021 * re paths.
2022 */
2023 static int
2024 altoffset(sop *scan, int offset)
2025 {
2026 int largest;
2027 int try;
2028 sop s;
2029
2030 /* If we gave up already on offsets, return */
2031 if (offset == -1)
2032 return -1;
2033
2034 largest = 0;
2035 try = 0;
2036 s = *scan++;
2037 while (OP(s) != (sop)O_QUEST && OP(s) != (sop)O_CH) {
2038 switch (OP(s)) {
2039 case OOR1:
2040 if (try > largest)
2041 largest = try;
2042 try = 0;
2043 break;
2044 case OQUEST_:
2045 case OCH_:
2046 try = altoffset(scan, try);
2047 if (try == -1)
2048 return -1;
2049 scan--;
2050 do {
2051 scan += OPND(s);
2052 s = *scan;
2053 if (OP(s) != (sop)O_QUEST &&
2054 OP(s) != (sop)O_CH && OP(s) != (sop)OOR2)
2055 return -1;
2056 } while (OP(s) != (sop)O_QUEST && OP(s) != (sop)O_CH);
2057 /* We must skip to the next position, or we'll
2058 * leave altoffset() too early.
2059 */
2060 scan++;
2061 break;
2062 case OANYOF:
2063 case OCHAR:
2064 case OANY:
2065 try++;
2066 case OBOW:
2067 case OEOW:
2068 case OWBND:
2069 case ONWBND:
2070 case OLPAREN:
2071 case ORPAREN:
2072 case OOR2:
2073 break;
2074 default:
2075 try = -1;
2076 break;
2077 }
2078 if (try == -1)
2079 return -1;
2080 s = *scan++;
2081 }
2082
2083 if (try > largest)
2084 largest = try;
2085
2086 return largest+offset;
2087 }
2088
2089 /*
2090 - computejumps - compute char jumps for BM scan
2091 == static void computejumps(struct parse *p, struct re_guts *g);
2092 *
2093 * This algorithm assumes g->must exists and is has size greater than
2094 * zero. It's based on the algorithm found on Computer Algorithms by
2095 * Sara Baase.
2096 *
2097 * A char jump is the number of characters one needs to jump based on
2098 * the value of the character from the text that was mismatched.
2099 */
2100 static void
2101 computejumps(struct parse *p, struct re_guts *g)
2102 {
2103 int ch;
2104 int mindex;
2105
2106 /* Avoid making errors worse */
2107 if (p->error != 0)
2108 return;
2109
2110 g->charjump = (int *)malloc((NC_MAX + 1) * sizeof(int));
2111 if (g->charjump == NULL) /* Not a fatal error */
2112 return;
2113 /* Adjust for signed chars, if necessary */
2114 g->charjump = &g->charjump[-(CHAR_MIN)];
2115
2116 /* If the character does not exist in the pattern, the jump
2117 * is equal to the number of characters in the pattern.
2118 */
2119 for (ch = CHAR_MIN; ch < (CHAR_MAX + 1); ch++)
2120 g->charjump[ch] = g->mlen;
2121
2122 /* If the character does exist, compute the jump that would
2123 * take us to the last character in the pattern equal to it
2124 * (notice that we match right to left, so that last character
2125 * is the first one that would be matched).
2126 */
2127 for (mindex = 0; mindex < g->mlen; mindex++)
2128 g->charjump[(int)g->must[mindex]] = g->mlen - mindex - 1;
2129 }
2130
2131 /*
2132 - computematchjumps - compute match jumps for BM scan
2133 == static void computematchjumps(struct parse *p, struct re_guts *g);
2134 *
2135 * This algorithm assumes g->must exists and is has size greater than
2136 * zero. It's based on the algorithm found on Computer Algorithms by
2137 * Sara Baase.
2138 *
2139 * A match jump is the number of characters one needs to advance based
2140 * on the already-matched suffix.
2141 * Notice that all values here are minus (g->mlen-1), because of the way
2142 * the search algorithm works.
2143 */
2144 static void
2145 computematchjumps(struct parse *p, struct re_guts *g)
2146 {
2147 int mindex; /* General "must" iterator */
2148 int suffix; /* Keeps track of matching suffix */
2149 int ssuffix; /* Keeps track of suffixes' suffix */
2150 int* pmatches; /* pmatches[k] points to the next i
2151 * such that i+1...mlen is a substring
2152 * of k+1...k+mlen-i-1
2153 */
2154
2155 /* Avoid making errors worse */
2156 if (p->error != 0)
2157 return;
2158
2159 pmatches = (int*) malloc(g->mlen * sizeof(int));
2160 if (pmatches == NULL) {
2161 g->matchjump = NULL;
2162 return;
2163 }
2164
2165 g->matchjump = (int*) malloc(g->mlen * sizeof(int));
2166 if (g->matchjump == NULL) { /* Not a fatal error */
2167 free(pmatches);
2168 return;
2169 }
2170
2171 /* Set maximum possible jump for each character in the pattern */
2172 for (mindex = 0; mindex < g->mlen; mindex++)
2173 g->matchjump[mindex] = 2*g->mlen - mindex - 1;
2174
2175 /* Compute pmatches[] */
2176 for (mindex = g->mlen - 1, suffix = g->mlen; mindex >= 0;
2177 mindex--, suffix--) {
2178 pmatches[mindex] = suffix;
2179
2180 /* If a mismatch is found, interrupting the substring,
2181 * compute the matchjump for that position. If no
2182 * mismatch is found, then a text substring mismatched
2183 * against the suffix will also mismatch against the
2184 * substring.
2185 */
2186 while (suffix < g->mlen
2187 && g->must[mindex] != g->must[suffix]) {
2188 g->matchjump[suffix] = MIN(g->matchjump[suffix],
2189 g->mlen - mindex - 1);
2190 suffix = pmatches[suffix];
2191 }
2192 }
2193
2194 /* Compute the matchjump up to the last substring found to jump
2195 * to the beginning of the largest must pattern prefix matching
2196 * it's own suffix.
2197 */
2198 for (mindex = 0; mindex <= suffix; mindex++)
2199 g->matchjump[mindex] = MIN(g->matchjump[mindex],
2200 g->mlen + suffix - mindex);
2201
2202 ssuffix = pmatches[suffix];
2203 while (suffix < g->mlen) {
2204 while (suffix <= ssuffix && suffix < g->mlen) {
2205 g->matchjump[suffix] = MIN(g->matchjump[suffix],
2206 g->mlen + ssuffix - suffix);
2207 suffix++;
2208 }
2209 if (suffix < g->mlen)
2210 ssuffix = pmatches[ssuffix];
2211 }
2212
2213 free(pmatches);
2214 }
2215
2216 /*
2217 - pluscount - count + nesting
2218 == static sopno pluscount(struct parse *p, struct re_guts *g);
2219 */
2220 static sopno /* nesting depth */
2221 pluscount(struct parse *p, struct re_guts *g)
2222 {
2223 sop *scan;
2224 sop s;
2225 sopno plusnest = 0;
2226 sopno maxnest = 0;
2227
2228 if (p->error != 0)
2229 return(0); /* there may not be an OEND */
2230
2231 scan = g->strip + 1;
2232 do {
2233 s = *scan++;
2234 switch (OP(s)) {
2235 case OPLUS_:
2236 plusnest++;
2237 break;
2238 case O_PLUS:
2239 if (plusnest > maxnest)
2240 maxnest = plusnest;
2241 plusnest--;
2242 break;
2243 }
2244 } while (OP(s) != OEND);
2245 if (plusnest != 0)
2246 g->iflags |= BAD;
2247 return(maxnest);
2248 }
2249