10 #if ( defined BB_GREP || defined BB_FIND || defined BB_SED)
12 /* This also tries to find a needle in a haystack, but uses
13 * real regular expressions.... The fake regular expression
14 * version of find_match lives in utility.c. Using this version
15 * will add 3.9k to busybox...
18 extern int find_match(char *haystack, char *needle, int ignoreCase)
22 re = regcomp( needle);
23 status = regexec(re, haystack, FALSE, ignoreCase);
29 /* This performs substitutions after a regexp match has been found.
30 * The new string is returned. It is malloc'ed, and do must be freed. */
31 extern int replace_match(char *haystack, char *needle, char *newNeedle, int ignoreCase)
35 char *s, buf[BUF_SIZE], *d = buf;
37 re = regcomp( needle);
38 status = regexec(re, haystack, FALSE, ignoreCase);
43 /* copy stuff from before the match */
44 while (s < re->startp[0])
46 /* substitute for the matched part */
47 regsub(re, newNeedle, d);
50 } while (regexec(re, s, FALSE, ignoreCase) == TRUE);
51 /* copy stuff from after the match */
52 while ( (*d++ = *s++) ) {}
55 strcpy(haystack, buf);
63 /* code swiped from elvis-tiny 1.4 (a clone of vi) and adjusted to
64 * suit the needs of busybox by Erik Andersen.
67 * "Elvis is freely redistributable, in either source form or executable form.
68 * There are no restrictions on how you may use it".
69 * Elvis was written by Steve Kirkendall <kirkenda@cs.pdx.edu>
72 * This file contains the code that compiles regular expressions and executes
73 * them. It supports the same syntax and features as vi's regular expression
74 * code. Specifically, the meta characters are:
75 * ^ matches the beginning of a line
76 * $ matches the end of a line
77 * \< matches the beginning of a word
78 * \> matches the end of a word
79 * . matches any single character
80 * [] matches any character in a character class
81 * \( delimits the start of a subexpression
82 * \) delimits the end of a subexpression
83 * * repeats the preceding 0 or more times
84 * NOTE: You cannot follow a \) with a *.
86 * The physical structure of a compiled RE is as follows:
87 * - First, there is a one-byte value that says how many character classes
88 * are used in this regular expression
89 * - Next, each character class is stored as a bitmap that is 256 bits
91 * - A mixture of literal characters and compiled meta characters follows.
92 * This begins with M_BEGIN(0) and ends with M_END(0). All meta chars
93 * are stored as a \n followed by a one-byte code, so they take up two
94 * bytes apiece. Literal characters take up one byte apiece. \n can't
95 * be used as a literal character.
101 static char *previous; /* the previous regexp, used when null regexp is given */
102 static char *previous1; /* a copy of the text from the previous substitution for regsub()*/
105 /* These are used to classify or recognize meta-characters */
107 #define BASE_META(m) ((m) - 256)
108 #define INT_META(c) ((c) + 256)
109 #define IS_META(m) ((m) >= 256)
110 #define IS_CLASS(m) ((m) >= M_CLASS(0) && (m) <= M_CLASS(9))
111 #define IS_START(m) ((m) >= M_START(0) && (m) <= M_START(9))
112 #define IS_END(m) ((m) >= M_END(0) && (m) <= M_END(9))
113 #define IS_CLOSURE(m) ((m) >= M_SPLAT && (m) <= M_QMARK)
114 #define ADD_META(s,m) (*(s)++ = META, *(s)++ = BASE_META(m))
115 #define GET_META(s) (*(s) == META ? INT_META(*++(s)) : *s)
117 /* These are the internal codes used for each type of meta-character */
118 #define M_BEGLINE 256 /* internal code for ^ */
119 #define M_ENDLINE 257 /* internal code for $ */
120 #define M_BEGWORD 258 /* internal code for \< */
121 #define M_ENDWORD 259 /* internal code for \> */
122 #define M_ANY 260 /* internal code for . */
123 #define M_SPLAT 261 /* internal code for * */
124 #define M_PLUS 262 /* internal code for \+ */
125 #define M_QMARK 263 /* internal code for \? */
126 #define M_CLASS(n) (264+(n)) /* internal code for [] */
127 #define M_START(n) (274+(n)) /* internal code for \( */
128 #define M_END(n) (284+(n)) /* internal code for \) */
130 /* These are used during compilation */
131 static int class_cnt; /* used to assign class IDs */
132 static int start_cnt; /* used to assign start IDs */
133 static int end_stk[NSUBEXP];/* used to assign end IDs */
135 static char *retext; /* points to the text being compiled */
137 /* error-handling stuff */
138 jmp_buf errorhandler;
139 #define FAIL(why) fprintf(stderr, why); longjmp(errorhandler, 1)
144 /* This function builds a bitmap for a particular class */
145 /* text -- start of the class */
146 /* bmap -- the bitmap */
147 static char *makeclass(char* text, char* bmap)
153 /* zero the bitmap */
154 for (i = 0; bmap && i < 32; i++)
159 /* see if we're going to complement this class */
166 /* add in the characters */
167 while (*text && *text != ']')
169 /* is this a span of characters? */
170 if (text[1] == '-' && text[2])
172 /* spans can't be backwards */
173 if (text[0] > text[2])
175 FAIL("Backwards span in []");
178 /* add each character in the span to the bitmap */
179 for (i = text[0]; bmap && i <= text[2]; i++)
181 bmap[i >> 3] |= (1 << (i & 7));
184 /* move past this span */
189 /* add this single character to the span */
193 bmap[i >> 3] |= (1 << (i & 7));
198 /* make sure the closing ] is missing */
204 /* if we're supposed to complement this class, then do so */
205 if (complement && bmap)
207 for (i = 0; i < 32; i++)
219 /* This function gets the next character or meta character from a string.
220 * The pointer is incremented by 1, or by 2 for \-quoted characters. For [],
221 * a bitmap is generated via makeclass() (if re is given), and the
222 * character-class text is skipped.
224 static int gettoken(sptr, re)
245 if (start_cnt >= NSUBEXP)
247 FAIL("Too many \\(s");
249 end_stk[end_sp++] = start_cnt;
250 return M_START(start_cnt++);
255 FAIL("Mismatched \\)");
257 return M_END(end_stk[--end_sp]);
279 if (*sptr == retext + 1)
299 /* make sure we don't have too many classes */
302 FAIL("Too many []s");
305 /* process the character list for this class */
308 /* generate the bitmap for this class */
309 *sptr = makeclass(*sptr, re->program + 1 + 32 * class_cnt);
313 /* skip to end of the class */
314 *sptr = makeclass(*sptr, (char *)0);
316 return M_CLASS(class_cnt++);
328 /* This function calculates the number of bytes that will be needed for a
329 * compiled RE. Its argument is the uncompiled version. It is not clever
330 * about catching syntax errors; that is done in a later pass.
332 static unsigned calcsize(text)
343 while ((token = gettoken(&text, (regexp *)0)) != 0)
349 else if (IS_META(token))
364 /*---------------------------------------------------------------------------*/
367 /* This function checks for a match between a character and a token which is
368 * known to represent a single character. It returns 0 if they match, or
371 static int match1(regexp* re, char ch, int token, int ignoreCase)
375 /* the end of a line can't match any RE of width 1 */
382 else if (IS_CLASS(token))
384 if (re->program[1 + 32 * (token - M_CLASS(0)) + (ch >> 3)] & (1 << (ch & 7)))
388 || (ignoreCase==TRUE && isupper(ch) && tolower(ch) == token))
397 /* This function checks characters up to and including the next closure, at
398 * which point it does a recursive call to check the rest of it. This function
399 * returns 0 if everything matches, or 1 if something doesn't match.
401 /* re -- the regular expression */
402 /* str -- the string */
403 /* prog -- a portion of re->program, an compiled RE */
404 /* here -- a portion of str, the string to compare it to */
405 static int match(regexp* re, char* str, char* prog, char* here, int ignoreCase)
411 for (token = GET_META(prog); !IS_CLOSURE(token); prog++, token = GET_META(prog))
415 /*case M_BEGLINE: can't happen; re->bol is used instead */
424 (isascii(here[-1]) && isalnum(here[-1]))))
429 if ((here[0] == '_' || isascii(here[0])) && isalnum(here[0]))
443 re->startp[token - M_START(0)] = (char *)here;
456 re->endp[token - M_END(0)] = (char *)here;
457 if (token == M_END(0))
463 default: /* literal, M_CLASS(n), or M_ANY */
464 if (match1(re, *here, token, ignoreCase) != 0)
472 /* step 1: see what we have to match against, and move "prog" to point
473 * the the remainder of the compiled RE.
476 prog++, token = GET_META(prog);
479 /* step 2: see how many times we can match that token against the string */
481 (closure != M_QMARK || nmatched < 1) && *here && match1(re, *here, token, ignoreCase) == 0;
486 /* step 3: try to match the remainder, and back off if it doesn't */
487 while (nmatched >= 0 && match(re, str, prog, here, ignoreCase) != 0)
493 /* so how did it work out? */
494 if (nmatched >= ((closure == M_PLUS) ? 1 : 0))
500 /* This function compiles a regexp. */
501 extern regexp *regcomp(char* text)
511 /* prepare for error handling */
513 if (setjmp(errorhandler))
522 /* if an empty regexp string was given, use the previous one */
527 FAIL("No previous RE");
531 else /* non-empty regexp given, so remember it */
535 previous = (char *)malloc((unsigned)(strlen(text) + 1));
537 strcpy(previous, text);
540 /* allocate memory */
545 size = calcsize(text) + sizeof(regexp);
546 re = (regexp *)malloc((unsigned)size);
550 FAIL("Not enough memory for this RE");
554 build = &re->program[1 + 32 * class_cnt];
555 re->program[0] = class_cnt;
556 for (token = 0; token < NSUBEXP; token++)
558 re->startp[token] = re->endp[token] = (char *)0;
568 for (token = M_START(0), peek = gettoken(&text, re);
570 token = peek, peek = gettoken(&text, re))
572 /* special processing for the closure operator */
573 if (IS_CLOSURE(peek))
575 /* detect misuse of closure operator */
578 FAIL("* or \\+ or \\? follows nothing");
580 else if (IS_META(token) && token != M_ANY && !IS_CLASS(token))
582 FAIL("* or \\+ or \\? can only follow a normal character or . or []");
585 /* it is okay -- make it prefix instead of postfix */
586 ADD_META(build, peek);
588 /* take care of "needfirst" - is this the first char? */
589 if (needfirst && peek == M_PLUS && !IS_META(token))
595 /* we used "peek" -- need to refill it */
596 peek = gettoken(&text, re);
597 if (IS_CLOSURE(peek))
599 FAIL("* or \\+ or \\? doubled up");
602 else if (!IS_META(token))
604 /* normal char is NOT argument of closure */
612 else if (token == M_ANY || IS_CLASS(token))
614 /* . or [] is NOT argument of closure */
619 /* the "token" character is not closure -- process it normally */
620 if (token == M_BEGLINE)
622 /* set the BOL flag instead of storing M_BEGLINE */
625 else if (IS_META(token))
627 ADD_META(build, token);
635 /* end it with a \) which MUST MATCH the opening \( */
636 ADD_META(build, M_END(0));
639 FAIL("Not enough \\)s");
648 /* This function searches through a string for text that matches an RE. */
649 /* re -- the compiled regexp to search for */
650 /* str -- the string to search through */
651 /* bol -- does str start at the beginning of a line? (boolean) */
652 /* ignoreCase -- ignoreCase or not */
653 extern int regexec(struct regexp* re, char* str, int bol, int ignoreCase)
655 char *prog; /* the entry point of re->program */
656 int len; /* length of the string */
659 /* if must start at the beginning of a line, and this isn't, then fail */
660 if (re->bol && bol==TRUE)
666 prog = re->program + 1 + 32 * re->program[0];
668 /* search for the RE in the string */
671 /* must occur at BOL */
673 && match1(re, *(char *)str, re->first, ignoreCase))/* wrong first letter? */
674 || len < re->minlen /* not long enough? */
675 || match(re, (char *)str, prog, str, ignoreCase)) /* doesn't match? */
676 return FALSE; /* THEN FAIL! */
678 else if (ignoreCase == FALSE)
680 /* can occur anywhere in the line, noignorecase */
681 for (here = (char *)str;
682 (re->first && re->first != *here)
683 || match(re, (char *)str, prog, here, ignoreCase);
686 if (len < re->minlen)
692 /* can occur anywhere in the line, ignorecase */
693 for (here = (char *)str;
694 (re->first && match1(re, *here, (int)re->first, ignoreCase))
695 || match(re, (char *)str, prog, here, ignoreCase);
698 if (len < re->minlen)
703 /* if we didn't fail, then we must have succeeded */
711 /* This performs substitutions after a regexp match has been found. */
712 extern void regsub(regexp* re, char* src, char* dst)
723 while ((c = *src++) != '\0')
725 /* recognize any meta characters */
735 end = cpy + strlen(cpy);
753 /* \0 thru \9 mean "copy subexpression" */
755 cpy = re->startp[(int)c];
756 end = re->endp[(int)c];
762 /* \U and \L mean "convert to upper/lowercase" */
768 /* \E ends the \U or \L */
772 /* "\&" means "original text" */
777 /* "\~" means "previous text, if any" */
781 /* ordinary char preceded by backslash */
788 /* ordinary character, so just copy it */
793 /* Note: to reach this point in the code, we must have evaded
794 * all "continue" statements. To do that, we must have hit
795 * a metacharacter that involves copying.
798 /* if there is nothing to copy, loop */
802 /* copy over a portion of the original */
809 /* convert to uppercase */
810 if (isascii(*cpy) && islower(*cpy))
812 *dst++ = toupper(*cpy);
823 /* convert to lowercase */
824 if (isascii(*cpy) && isupper(*cpy))
826 *dst++ = tolower(*cpy);
836 /* copy without any conversion */
840 /* \u and \l end automatically after the first char */
841 if (mod && (mod == 'u' || mod == 'l'))
849 /* remember what text we inserted this time */
852 previous1 = (char *)malloc((unsigned)(strlen(start) + 1));
854 strcpy(previous1, start);
858 #endif /* BB_REGEXP */