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