1 /* vi: set sw=4 ts=4: */
11 #if ( defined BB_GREP || defined BB_SED)
13 /* This also tries to find a needle in a haystack, but uses
14 * real regular expressions.... The fake regular expression
15 * version of find_match lives in utility.c. Using this version
16 * will add 3.9k to busybox...
19 extern int find_match(char *haystack, char *needle, int ignoreCase)
25 status = regexec(re, haystack, FALSE, ignoreCase);
31 /* This performs substitutions after a regexp match has been found.
32 * The new string is returned. It is malloc'ed, and do must be freed. */
33 extern int replace_match(char *haystack, char *needle, char *newNeedle,
38 char *s, buf[BUF_SIZE], *d = buf;
41 status = regexec(re, haystack, FALSE, ignoreCase);
46 /* copy stuff from before the match */
47 while (s < re->startp[0])
49 /* substitute for the matched part */
50 regsub(re, newNeedle, d);
53 } while (regexec(re, s, FALSE, ignoreCase) == TRUE);
54 /* copy stuff from after the match */
55 while ((*d++ = *s++)) {
58 strcpy(haystack, buf);
66 /* code swiped from elvis-tiny 1.4 (a clone of vi) and adjusted to
67 * suit the needs of busybox by Erik Andersen.
70 * "Elvis is freely redistributable, in either source form or executable form.
71 * There are no restrictions on how you may use it".
72 * Elvis was written by Steve Kirkendall <kirkenda@cs.pdx.edu>
75 * This file contains the code that compiles regular expressions and executes
76 * them. It supports the same syntax and features as vi's regular expression
77 * code. Specifically, the meta characters are:
78 * ^ matches the beginning of a line
79 * $ matches the end of a line
80 * \< matches the beginning of a word
81 * \> matches the end of a word
82 * . matches any single character
83 * [] matches any character in a character class
84 * \( delimits the start of a subexpression
85 * \) delimits the end of a subexpression
86 * * repeats the preceding 0 or more times
87 * NOTE: You cannot follow a \) with a *.
89 * The physical structure of a compiled RE is as follows:
90 * - First, there is a one-byte value that says how many character classes
91 * are used in this regular expression
92 * - Next, each character class is stored as a bitmap that is 256 bits
94 * - A mixture of literal characters and compiled meta characters follows.
95 * This begins with M_BEGIN(0) and ends with M_END(0). All meta chars
96 * are stored as a \n followed by a one-byte code, so they take up two
97 * bytes apiece. Literal characters take up one byte apiece. \n can't
98 * be used as a literal character.
104 static char *previous; /* the previous regexp, used when null regexp is given */
107 static char *previous1; /* a copy of the text from the previous substitution for regsub() */
111 /* These are used to classify or recognize meta-characters */
113 #define BASE_META(m) ((m) - 256)
114 #define INT_META(c) ((c) + 256)
115 #define IS_META(m) ((m) >= 256)
116 #define IS_CLASS(m) ((m) >= M_CLASS(0) && (m) <= M_CLASS(9))
117 #define IS_START(m) ((m) >= M_START(0) && (m) <= M_START(9))
118 #define IS_END(m) ((m) >= M_END(0) && (m) <= M_END(9))
119 #define IS_CLOSURE(m) ((m) >= M_SPLAT && (m) <= M_QMARK)
120 #define ADD_META(s,m) (*(s)++ = META, *(s)++ = BASE_META(m))
121 #define GET_META(s) (*(s) == META ? INT_META(*++(s)) : *s)
123 /* These are the internal codes used for each type of meta-character */
124 #define M_BEGLINE 256 /* internal code for ^ */
125 #define M_ENDLINE 257 /* internal code for $ */
126 #define M_BEGWORD 258 /* internal code for \< */
127 #define M_ENDWORD 259 /* internal code for \> */
128 #define M_ANY 260 /* internal code for . */
129 #define M_SPLAT 261 /* internal code for * */
130 #define M_PLUS 262 /* internal code for \+ */
131 #define M_QMARK 263 /* internal code for \? */
132 #define M_CLASS(n) (264+(n)) /* internal code for [] */
133 #define M_START(n) (274+(n)) /* internal code for \( */
134 #define M_END(n) (284+(n)) /* internal code for \) */
136 /* These are used during compilation */
137 static int class_cnt; /* used to assign class IDs */
138 static int start_cnt; /* used to assign start IDs */
139 static int end_stk[NSUBEXP]; /* used to assign end IDs */
141 static char *retext; /* points to the text being compiled */
143 /* error-handling stuff */
144 jmp_buf errorhandler;
146 #define FAIL(why) do {fprintf(stderr, why); longjmp(errorhandler, 1);} while (0)
151 /* This function builds a bitmap for a particular class */
152 /* text -- start of the class */
153 /* bmap -- the bitmap */
154 static char *makeclass(char *text, char *bmap)
160 /* zero the bitmap */
161 for (i = 0; bmap && i < 32; i++) {
165 /* see if we're going to complement this class */
171 /* add in the characters */
172 while (*text && *text != ']') {
173 /* is this a span of characters? */
174 if (text[1] == '-' && text[2]) {
175 /* spans can't be backwards */
176 if (text[0] > text[2]) {
177 FAIL("Backwards span in []");
180 /* add each character in the span to the bitmap */
181 for (i = text[0]; bmap && i <= text[2]; i++) {
182 bmap[i >> 3] |= (1 << (i & 7));
185 /* move past this span */
188 /* add this single character to the span */
191 bmap[i >> 3] |= (1 << (i & 7));
196 /* make sure the closing ] is missing */
197 if (*text++ != ']') {
201 /* if we're supposed to complement this class, then do so */
202 if (complement && bmap) {
203 for (i = 0; i < 32; i++) {
214 /* This function gets the next character or meta character from a string.
215 * The pointer is incremented by 1, or by 2 for \-quoted characters. For [],
216 * a bitmap is generated via makeclass() (if re is given), and the
217 * character-class text is skipped.
219 static int gettoken(sptr, re)
238 if (start_cnt >= NSUBEXP) {
239 FAIL("Too many \\(s");
241 end_stk[end_sp++] = start_cnt;
242 return M_START(start_cnt++);
246 FAIL("Mismatched \\)");
248 return M_END(end_stk[--end_sp]);
268 if (*sptr == retext + 1) {
286 /* make sure we don't have too many classes */
287 if (class_cnt >= 10) {
288 FAIL("Too many []s");
291 /* process the character list for this class */
293 /* generate the bitmap for this class */
294 *sptr = makeclass(*sptr, re->program + 1 + 32 * class_cnt);
296 /* skip to end of the class */
297 *sptr = makeclass(*sptr, (char *) 0);
299 return M_CLASS(class_cnt++);
310 /* This function calculates the number of bytes that will be needed for a
311 * compiled RE. Its argument is the uncompiled version. It is not clever
312 * about catching syntax errors; that is done in a later pass.
314 static unsigned calcsize(text)
325 while ((token = gettoken(&text, (regexp *) 0)) != 0) {
326 if (IS_CLASS(token)) {
328 } else if (IS_META(token)) {
340 /*---------------------------------------------------------------------------*/
343 /* This function checks for a match between a character and a token which is
344 * known to represent a single character. It returns 0 if they match, or
347 static int match1(regexp * re, char ch, int token, int ignoreCase)
350 /* the end of a line can't match any RE of width 1 */
353 if (token == M_ANY) {
355 } else if (IS_CLASS(token)) {
357 program[1 + 32 * (token - M_CLASS(0)) +
358 (ch >> 3)] & (1 << (ch & 7)))
361 //fprintf(stderr, "match1: ch='%c' token='%c': ", ch, token);
363 || (ignoreCase == TRUE && tolower(ch) == tolower(token))) {
364 //fprintf(stderr, "match\n");
367 //fprintf(stderr, "no match\n");
373 /* This function checks characters up to and including the next closure, at
374 * which point it does a recursive call to check the rest of it. This function
375 * returns 0 if everything matches, or 1 if something doesn't match.
377 /* re -- the regular expression */
378 /* str -- the string */
379 /* prog -- a portion of re->program, an compiled RE */
380 /* here -- a portion of str, the string to compare it to */
381 static int match(regexp * re, char *str, char *prog, char *here,
388 for (token = GET_META(prog); !IS_CLOSURE(token);
389 prog++, token = GET_META(prog)) {
391 /*case M_BEGLINE: can't happen; re->bol is used instead */
400 (isascii(here[-1]) && isalnum(here[-1])))) return 1;
404 if ((here[0] == '_' || isascii(here[0])) && isalnum(here[0]))
418 re->startp[token - M_START(0)] = (char *) here;
431 re->endp[token - M_END(0)] = (char *) here;
432 if (token == M_END(0)) {
437 default: /* literal, M_CLASS(n), or M_ANY */
438 if (match1(re, *here, token, ignoreCase) != 0)
446 /* step 1: see what we have to match against, and move "prog" to point
447 * the the remainder of the compiled RE.
450 prog++, token = GET_META(prog);
453 /* step 2: see how many times we can match that token against the string */
455 (closure != M_QMARK || nmatched < 1) && *here
456 && match1(re, *here, token, ignoreCase) == 0; nmatched++, here++) {
459 /* step 3: try to match the remainder, and back off if it doesn't */
460 while (nmatched >= 0 && match(re, str, prog, here, ignoreCase) != 0) {
465 /* so how did it work out? */
466 if (nmatched >= ((closure == M_PLUS) ? 1 : 0))
472 /* This function compiles a regexp. */
473 extern regexp *regcomp(char *text)
480 regexp *re; // Ignore compiler whining. If we longjmp, we don't use re anymore.
483 /* prepare for error handling */
485 if (setjmp(errorhandler)) {
492 /* if an empty regexp string was given, use the previous one */
495 FAIL("No previous RE");
498 } else { /* non-empty regexp given, so remember it */
502 previous = (char *) malloc((unsigned) (strlen(text) + 1));
504 strcpy(previous, text);
507 /* allocate memory */
512 size = calcsize(text) + sizeof(regexp);
513 re = (regexp *) malloc((unsigned) size);
516 FAIL("Not enough memory for this RE");
520 build = &re->program[1 + 32 * class_cnt];
521 re->program[0] = class_cnt;
522 for (token = 0; token < NSUBEXP; token++) {
523 re->startp[token] = re->endp[token] = (char *) 0;
533 for (token = M_START(0), peek = gettoken(&text, re);
534 token; token = peek, peek = gettoken(&text, re)) {
535 /* special processing for the closure operator */
536 if (IS_CLOSURE(peek)) {
537 /* detect misuse of closure operator */
538 if (IS_START(token)) {
539 FAIL("* or \\+ or \\? follows nothing");
541 else if (IS_META(token) && token != M_ANY
542 && !IS_CLASS(token)) {
544 ("* or \\+ or \\? can only follow a normal character or . or []");
547 /* it is okay -- make it prefix instead of postfix */
548 ADD_META(build, peek);
550 /* take care of "needfirst" - is this the first char? */
551 if (needfirst && peek == M_PLUS && !IS_META(token)) {
556 /* we used "peek" -- need to refill it */
557 peek = gettoken(&text, re);
558 if (IS_CLOSURE(peek)) {
559 FAIL("* or \\+ or \\? doubled up");
561 } else if (!IS_META(token)) {
562 /* normal char is NOT argument of closure */
568 } else if (token == M_ANY || IS_CLASS(token)) {
569 /* . or [] is NOT argument of closure */
574 /* the "token" character is not closure -- process it normally */
575 if (token == M_BEGLINE) {
576 /* set the BOL flag instead of storing M_BEGLINE */
578 } else if (IS_META(token)) {
579 ADD_META(build, token);
585 /* end it with a \) which MUST MATCH the opening \( */
586 ADD_META(build, M_END(0));
588 FAIL("Not enough \\)s");
597 /* This function searches through a string for text that matches an RE. */
598 /* re -- the compiled regexp to search for */
599 /* str -- the string to search through */
600 /* bol -- does str start at the beginning of a line? (boolean) */
601 /* ignoreCase -- ignoreCase or not */
602 extern int regexec(struct regexp *re, char *str, int bol, int ignoreCase)
604 char *prog; /* the entry point of re->program */
605 int len; /* length of the string */
608 /* if must start at the beginning of a line, and this isn't, then fail */
609 if (re->bol && bol == TRUE) {
614 prog = re->program + 1 + 32 * re->program[0];
616 /* search for the RE in the string */
618 /* must occur at BOL */
619 if ((re->first && match1(re, *(char *) str, re->first, ignoreCase)) /* wrong first letter? */
620 ||len < re->minlen /* not long enough? */
621 || match(re, (char *) str, prog, str, ignoreCase)) /* doesn't match? */
622 return FALSE; /* THEN FAIL! */
623 } else if (ignoreCase == FALSE) {
624 /* can occur anywhere in the line, noignorecase */
625 for (here = (char *) str; (re->first && re->first != *here)
626 || match(re, (char *) str, prog, here, ignoreCase);
628 if (len < re->minlen)
632 /* can occur anywhere in the line, ignorecase */
633 for (here = (char *) str;
634 (re->first && match1(re, *here, (int) re->first, ignoreCase))
635 || match(re, (char *) str, prog, here, ignoreCase);
637 if (len < re->minlen)
642 /* if we didn't fail, then we must have succeeded */
650 /* This performs substitutions after a regexp match has been found. */
651 extern void regsub(regexp * re, char *src, char *dst)
662 while ((c = *src++) != '\0') {
663 /* recognize any meta characters */
667 } else if (c == '~') {
670 end = cpy + strlen(cpy);
671 } else if (c == '\\') {
684 /* \0 thru \9 mean "copy subexpression" */
686 cpy = re->startp[(int) c];
687 end = re->endp[(int) c];
693 /* \U and \L mean "convert to upper/lowercase" */
699 /* \E ends the \U or \L */
703 /* "\&" means "original text" */
708 /* "\~" means "previous text, if any" */
712 /* ordinary char preceded by backslash */
717 /* ordinary character, so just copy it */
722 /* Note: to reach this point in the code, we must have evaded
723 * all "continue" statements. To do that, we must have hit
724 * a metacharacter that involves copying.
727 /* if there is nothing to copy, loop */
731 /* copy over a portion of the original */
736 /* convert to uppercase */
737 if (isascii(*cpy) && islower(*cpy)) {
738 *dst++ = toupper(*cpy);
747 /* convert to lowercase */
748 if (isascii(*cpy) && isupper(*cpy)) {
749 *dst++ = tolower(*cpy);
757 /* copy without any conversion */
761 /* \u and \l end automatically after the first char */
762 if (mod && (mod == 'u' || mod == 'l')) {
769 /* remember what text we inserted this time */
772 previous1 = (char *) malloc((unsigned) (strlen(start) + 1));
774 strcpy(previous1, start);
778 #endif /* BB_REGEXP */