10 #if ( defined BB_GREP || 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++) ) {}
54 strcpy(haystack, buf);
62 /* code swiped from elvis-tiny 1.4 (a clone of vi) and adjusted to
63 * suit the needs of busybox by Erik Andersen.
66 * "Elvis is freely redistributable, in either source form or executable form.
67 * There are no restrictions on how you may use it".
68 * Elvis was written by Steve Kirkendall <kirkenda@cs.pdx.edu>
71 * This file contains the code that compiles regular expressions and executes
72 * them. It supports the same syntax and features as vi's regular expression
73 * code. Specifically, the meta characters are:
74 * ^ matches the beginning of a line
75 * $ matches the end of a line
76 * \< matches the beginning of a word
77 * \> matches the end of a word
78 * . matches any single character
79 * [] matches any character in a character class
80 * \( delimits the start of a subexpression
81 * \) delimits the end of a subexpression
82 * * repeats the preceding 0 or more times
83 * NOTE: You cannot follow a \) with a *.
85 * The physical structure of a compiled RE is as follows:
86 * - First, there is a one-byte value that says how many character classes
87 * are used in this regular expression
88 * - Next, each character class is stored as a bitmap that is 256 bits
90 * - A mixture of literal characters and compiled meta characters follows.
91 * This begins with M_BEGIN(0) and ends with M_END(0). All meta chars
92 * are stored as a \n followed by a one-byte code, so they take up two
93 * bytes apiece. Literal characters take up one byte apiece. \n can't
94 * be used as a literal character.
100 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()*/
106 /* These are used to classify or recognize meta-characters */
108 #define BASE_META(m) ((m) - 256)
109 #define INT_META(c) ((c) + 256)
110 #define IS_META(m) ((m) >= 256)
111 #define IS_CLASS(m) ((m) >= M_CLASS(0) && (m) <= M_CLASS(9))
112 #define IS_START(m) ((m) >= M_START(0) && (m) <= M_START(9))
113 #define IS_END(m) ((m) >= M_END(0) && (m) <= M_END(9))
114 #define IS_CLOSURE(m) ((m) >= M_SPLAT && (m) <= M_QMARK)
115 #define ADD_META(s,m) (*(s)++ = META, *(s)++ = BASE_META(m))
116 #define GET_META(s) (*(s) == META ? INT_META(*++(s)) : *s)
118 /* These are the internal codes used for each type of meta-character */
119 #define M_BEGLINE 256 /* internal code for ^ */
120 #define M_ENDLINE 257 /* internal code for $ */
121 #define M_BEGWORD 258 /* internal code for \< */
122 #define M_ENDWORD 259 /* internal code for \> */
123 #define M_ANY 260 /* internal code for . */
124 #define M_SPLAT 261 /* internal code for * */
125 #define M_PLUS 262 /* internal code for \+ */
126 #define M_QMARK 263 /* internal code for \? */
127 #define M_CLASS(n) (264+(n)) /* internal code for [] */
128 #define M_START(n) (274+(n)) /* internal code for \( */
129 #define M_END(n) (284+(n)) /* internal code for \) */
131 /* These are used during compilation */
132 static int class_cnt; /* used to assign class IDs */
133 static int start_cnt; /* used to assign start IDs */
134 static int end_stk[NSUBEXP];/* used to assign end IDs */
136 static char *retext; /* points to the text being compiled */
138 /* error-handling stuff */
139 jmp_buf errorhandler;
140 #define FAIL(why) do {fprintf(stderr, why); longjmp(errorhandler, 1);} while (0)
145 /* This function builds a bitmap for a particular class */
146 /* text -- start of the class */
147 /* bmap -- the bitmap */
148 static char *makeclass(char* text, char* bmap)
154 /* zero the bitmap */
155 for (i = 0; bmap && i < 32; i++)
160 /* see if we're going to complement this class */
167 /* add in the characters */
168 while (*text && *text != ']')
170 /* is this a span of characters? */
171 if (text[1] == '-' && text[2])
173 /* spans can't be backwards */
174 if (text[0] > text[2])
176 FAIL("Backwards span in []");
179 /* add each character in the span to the bitmap */
180 for (i = text[0]; bmap && i <= text[2]; i++)
182 bmap[i >> 3] |= (1 << (i & 7));
185 /* move past this span */
190 /* add this single character to the span */
194 bmap[i >> 3] |= (1 << (i & 7));
199 /* make sure the closing ] is missing */
205 /* if we're supposed to complement this class, then do so */
206 if (complement && bmap)
208 for (i = 0; i < 32; i++)
220 /* This function gets the next character or meta character from a string.
221 * The pointer is incremented by 1, or by 2 for \-quoted characters. For [],
222 * a bitmap is generated via makeclass() (if re is given), and the
223 * character-class text is skipped.
225 static int gettoken(sptr, re)
246 if (start_cnt >= NSUBEXP)
248 FAIL("Too many \\(s");
250 end_stk[end_sp++] = start_cnt;
251 return M_START(start_cnt++);
256 FAIL("Mismatched \\)");
258 return M_END(end_stk[--end_sp]);
280 if (*sptr == retext + 1)
300 /* make sure we don't have too many classes */
303 FAIL("Too many []s");
306 /* process the character list for this class */
309 /* generate the bitmap for this class */
310 *sptr = makeclass(*sptr, re->program + 1 + 32 * class_cnt);
314 /* skip to end of the class */
315 *sptr = makeclass(*sptr, (char *)0);
317 return M_CLASS(class_cnt++);
329 /* This function calculates the number of bytes that will be needed for a
330 * compiled RE. Its argument is the uncompiled version. It is not clever
331 * about catching syntax errors; that is done in a later pass.
333 static unsigned calcsize(text)
344 while ((token = gettoken(&text, (regexp *)0)) != 0)
350 else if (IS_META(token))
365 /*---------------------------------------------------------------------------*/
368 /* This function checks for a match between a character and a token which is
369 * known to represent a single character. It returns 0 if they match, or
372 static int match1(regexp* re, char ch, int token, int ignoreCase)
376 /* the end of a line can't match any RE of width 1 */
383 else if (IS_CLASS(token))
385 if (re->program[1 + 32 * (token - M_CLASS(0)) + (ch >> 3)] & (1 << (ch & 7)))
389 || (ignoreCase==TRUE && isupper(ch) && tolower(ch) == token))
398 /* This function checks characters up to and including the next closure, at
399 * which point it does a recursive call to check the rest of it. This function
400 * returns 0 if everything matches, or 1 if something doesn't match.
402 /* re -- the regular expression */
403 /* str -- the string */
404 /* prog -- a portion of re->program, an compiled RE */
405 /* here -- a portion of str, the string to compare it to */
406 static int match(regexp* re, char* str, char* prog, char* here, int ignoreCase)
412 for (token = GET_META(prog); !IS_CLOSURE(token); prog++, token = GET_META(prog))
416 /*case M_BEGLINE: can't happen; re->bol is used instead */
425 (isascii(here[-1]) && isalnum(here[-1]))))
430 if ((here[0] == '_' || isascii(here[0])) && isalnum(here[0]))
444 re->startp[token - M_START(0)] = (char *)here;
457 re->endp[token - M_END(0)] = (char *)here;
458 if (token == M_END(0))
464 default: /* literal, M_CLASS(n), or M_ANY */
465 if (match1(re, *here, token, ignoreCase) != 0)
473 /* step 1: see what we have to match against, and move "prog" to point
474 * the the remainder of the compiled RE.
477 prog++, token = GET_META(prog);
480 /* step 2: see how many times we can match that token against the string */
482 (closure != M_QMARK || nmatched < 1) && *here && match1(re, *here, token, ignoreCase) == 0;
487 /* step 3: try to match the remainder, and back off if it doesn't */
488 while (nmatched >= 0 && match(re, str, prog, here, ignoreCase) != 0)
494 /* so how did it work out? */
495 if (nmatched >= ((closure == M_PLUS) ? 1 : 0))
501 /* This function compiles a regexp. */
502 extern regexp *regcomp(char* text)
509 regexp *re; // Ignore compiler whining. If we longjmp, we don't use re anymore.
512 /* prepare for error handling */
514 if (setjmp(errorhandler))
523 /* if an empty regexp string was given, use the previous one */
528 FAIL("No previous RE");
532 else /* non-empty regexp given, so remember it */
536 previous = (char *)malloc((unsigned)(strlen(text) + 1));
538 strcpy(previous, text);
541 /* allocate memory */
546 size = calcsize(text) + sizeof(regexp);
547 re = (regexp *)malloc((unsigned)size);
551 FAIL("Not enough memory for this RE");
555 build = &re->program[1 + 32 * class_cnt];
556 re->program[0] = class_cnt;
557 for (token = 0; token < NSUBEXP; token++)
559 re->startp[token] = re->endp[token] = (char *)0;
569 for (token = M_START(0), peek = gettoken(&text, re);
571 token = peek, peek = gettoken(&text, re))
573 /* special processing for the closure operator */
574 if (IS_CLOSURE(peek))
576 /* detect misuse of closure operator */
579 FAIL("* or \\+ or \\? follows nothing");
581 else if (IS_META(token) && token != M_ANY && !IS_CLASS(token))
583 FAIL("* or \\+ or \\? can only follow a normal character or . or []");
586 /* it is okay -- make it prefix instead of postfix */
587 ADD_META(build, peek);
589 /* take care of "needfirst" - is this the first char? */
590 if (needfirst && peek == M_PLUS && !IS_META(token))
596 /* we used "peek" -- need to refill it */
597 peek = gettoken(&text, re);
598 if (IS_CLOSURE(peek))
600 FAIL("* or \\+ or \\? doubled up");
603 else if (!IS_META(token))
605 /* normal char is NOT argument of closure */
613 else if (token == M_ANY || IS_CLASS(token))
615 /* . or [] is NOT argument of closure */
620 /* the "token" character is not closure -- process it normally */
621 if (token == M_BEGLINE)
623 /* set the BOL flag instead of storing M_BEGLINE */
626 else if (IS_META(token))
628 ADD_META(build, token);
636 /* end it with a \) which MUST MATCH the opening \( */
637 ADD_META(build, M_END(0));
640 FAIL("Not enough \\)s");
649 /* This function searches through a string for text that matches an RE. */
650 /* re -- the compiled regexp to search for */
651 /* str -- the string to search through */
652 /* bol -- does str start at the beginning of a line? (boolean) */
653 /* ignoreCase -- ignoreCase or not */
654 extern int regexec(struct regexp* re, char* str, int bol, int ignoreCase)
656 char *prog; /* the entry point of re->program */
657 int len; /* length of the string */
660 /* if must start at the beginning of a line, and this isn't, then fail */
661 if (re->bol && bol==TRUE)
667 prog = re->program + 1 + 32 * re->program[0];
669 /* search for the RE in the string */
672 /* must occur at BOL */
674 && match1(re, *(char *)str, re->first, ignoreCase))/* wrong first letter? */
675 || len < re->minlen /* not long enough? */
676 || match(re, (char *)str, prog, str, ignoreCase)) /* doesn't match? */
677 return FALSE; /* THEN FAIL! */
679 else if (ignoreCase == FALSE)
681 /* can occur anywhere in the line, noignorecase */
682 for (here = (char *)str;
683 (re->first && re->first != *here)
684 || match(re, (char *)str, prog, here, ignoreCase);
687 if (len < re->minlen)
693 /* can occur anywhere in the line, ignorecase */
694 for (here = (char *)str;
695 (re->first && match1(re, *here, (int)re->first, ignoreCase))
696 || match(re, (char *)str, prog, here, ignoreCase);
699 if (len < re->minlen)
704 /* if we didn't fail, then we must have succeeded */
712 /* This performs substitutions after a regexp match has been found. */
713 extern void regsub(regexp* re, char* src, char* dst)
724 while ((c = *src++) != '\0')
726 /* recognize any meta characters */
736 end = cpy + strlen(cpy);
754 /* \0 thru \9 mean "copy subexpression" */
756 cpy = re->startp[(int)c];
757 end = re->endp[(int)c];
763 /* \U and \L mean "convert to upper/lowercase" */
769 /* \E ends the \U or \L */
773 /* "\&" means "original text" */
778 /* "\~" means "previous text, if any" */
782 /* ordinary char preceded by backslash */
789 /* ordinary character, so just copy it */
794 /* Note: to reach this point in the code, we must have evaded
795 * all "continue" statements. To do that, we must have hit
796 * a metacharacter that involves copying.
799 /* if there is nothing to copy, loop */
803 /* copy over a portion of the original */
810 /* convert to uppercase */
811 if (isascii(*cpy) && islower(*cpy))
813 *dst++ = toupper(*cpy);
824 /* convert to lowercase */
825 if (isascii(*cpy) && isupper(*cpy))
827 *dst++ = tolower(*cpy);
837 /* copy without any conversion */
841 /* \u and \l end automatically after the first char */
842 if (mod && (mod == 'u' || mod == 'l'))
850 /* remember what text we inserted this time */
853 previous1 = (char *)malloc((unsigned)(strlen(start) + 1));
855 strcpy(previous1, start);
859 #endif /* BB_REGEXP */