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++) ) {}
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 */
101 static char *previous1; /* a copy of the text from the previous substitution for regsub()*/
104 /* These are used to classify or recognize meta-characters */
106 #define BASE_META(m) ((m) - 256)
107 #define INT_META(c) ((c) + 256)
108 #define IS_META(m) ((m) >= 256)
109 #define IS_CLASS(m) ((m) >= M_CLASS(0) && (m) <= M_CLASS(9))
110 #define IS_START(m) ((m) >= M_START(0) && (m) <= M_START(9))
111 #define IS_END(m) ((m) >= M_END(0) && (m) <= M_END(9))
112 #define IS_CLOSURE(m) ((m) >= M_SPLAT && (m) <= M_QMARK)
113 #define ADD_META(s,m) (*(s)++ = META, *(s)++ = BASE_META(m))
114 #define GET_META(s) (*(s) == META ? INT_META(*++(s)) : *s)
116 /* These are the internal codes used for each type of meta-character */
117 #define M_BEGLINE 256 /* internal code for ^ */
118 #define M_ENDLINE 257 /* internal code for $ */
119 #define M_BEGWORD 258 /* internal code for \< */
120 #define M_ENDWORD 259 /* internal code for \> */
121 #define M_ANY 260 /* internal code for . */
122 #define M_SPLAT 261 /* internal code for * */
123 #define M_PLUS 262 /* internal code for \+ */
124 #define M_QMARK 263 /* internal code for \? */
125 #define M_CLASS(n) (264+(n)) /* internal code for [] */
126 #define M_START(n) (274+(n)) /* internal code for \( */
127 #define M_END(n) (284+(n)) /* internal code for \) */
129 /* These are used during compilation */
130 static int class_cnt; /* used to assign class IDs */
131 static int start_cnt; /* used to assign start IDs */
132 static int end_stk[NSUBEXP];/* used to assign end IDs */
134 static char *retext; /* points to the text being compiled */
136 /* error-handling stuff */
137 jmp_buf errorhandler;
138 #define FAIL(why) fprintf(stderr, why); longjmp(errorhandler, 1)
143 /* This function builds a bitmap for a particular class */
144 /* text -- start of the class */
145 /* bmap -- the bitmap */
146 static char *makeclass(char* text, char* bmap)
152 /* zero the bitmap */
153 for (i = 0; bmap && i < 32; i++)
158 /* see if we're going to complement this class */
165 /* add in the characters */
166 while (*text && *text != ']')
168 /* is this a span of characters? */
169 if (text[1] == '-' && text[2])
171 /* spans can't be backwards */
172 if (text[0] > text[2])
174 FAIL("Backwards span in []");
177 /* add each character in the span to the bitmap */
178 for (i = text[0]; bmap && i <= text[2]; i++)
180 bmap[i >> 3] |= (1 << (i & 7));
183 /* move past this span */
188 /* add this single character to the span */
192 bmap[i >> 3] |= (1 << (i & 7));
197 /* make sure the closing ] is missing */
203 /* if we're supposed to complement this class, then do so */
204 if (complement && bmap)
206 for (i = 0; i < 32; i++)
218 /* This function gets the next character or meta character from a string.
219 * The pointer is incremented by 1, or by 2 for \-quoted characters. For [],
220 * a bitmap is generated via makeclass() (if re is given), and the
221 * character-class text is skipped.
223 static int gettoken(sptr, re)
244 if (start_cnt >= NSUBEXP)
246 FAIL("Too many \\(s");
248 end_stk[end_sp++] = start_cnt;
249 return M_START(start_cnt++);
254 FAIL("Mismatched \\)");
256 return M_END(end_stk[--end_sp]);
278 if (*sptr == retext + 1)
298 /* make sure we don't have too many classes */
301 FAIL("Too many []s");
304 /* process the character list for this class */
307 /* generate the bitmap for this class */
308 *sptr = makeclass(*sptr, re->program + 1 + 32 * class_cnt);
312 /* skip to end of the class */
313 *sptr = makeclass(*sptr, (char *)0);
315 return M_CLASS(class_cnt++);
327 /* This function calculates the number of bytes that will be needed for a
328 * compiled RE. Its argument is the uncompiled version. It is not clever
329 * about catching syntax errors; that is done in a later pass.
331 static unsigned calcsize(text)
342 while ((token = gettoken(&text, (regexp *)0)) != 0)
348 else if (IS_META(token))
363 /*---------------------------------------------------------------------------*/
366 /* This function checks for a match between a character and a token which is
367 * known to represent a single character. It returns 0 if they match, or
370 static int match1(regexp* re, char ch, int token, int ignoreCase)
374 /* the end of a line can't match any RE of width 1 */
381 else if (IS_CLASS(token))
383 if (re->program[1 + 32 * (token - M_CLASS(0)) + (ch >> 3)] & (1 << (ch & 7)))
387 || (ignoreCase==TRUE && isupper(ch) && tolower(ch) == token))
396 /* This function checks characters up to and including the next closure, at
397 * which point it does a recursive call to check the rest of it. This function
398 * returns 0 if everything matches, or 1 if something doesn't match.
400 /* re -- the regular expression */
401 /* str -- the string */
402 /* prog -- a portion of re->program, an compiled RE */
403 /* here -- a portion of str, the string to compare it to */
404 static int match(regexp* re, char* str, char* prog, char* here, int ignoreCase)
410 for (token = GET_META(prog); !IS_CLOSURE(token); prog++, token = GET_META(prog))
414 /*case M_BEGLINE: can't happen; re->bol is used instead */
423 (isascii(here[-1]) && isalnum(here[-1]))))
428 if ((here[0] == '_' || isascii(here[0])) && isalnum(here[0]))
442 re->startp[token - M_START(0)] = (char *)here;
455 re->endp[token - M_END(0)] = (char *)here;
456 if (token == M_END(0))
462 default: /* literal, M_CLASS(n), or M_ANY */
463 if (match1(re, *here, token, ignoreCase) != 0)
471 /* step 1: see what we have to match against, and move "prog" to point
472 * the the remainder of the compiled RE.
475 prog++, token = GET_META(prog);
478 /* step 2: see how many times we can match that token against the string */
480 (closure != M_QMARK || nmatched < 1) && *here && match1(re, *here, token, ignoreCase) == 0;
485 /* step 3: try to match the remainder, and back off if it doesn't */
486 while (nmatched >= 0 && match(re, str, prog, here, ignoreCase) != 0)
492 /* so how did it work out? */
493 if (nmatched >= ((closure == M_PLUS) ? 1 : 0))
499 /* This function compiles a regexp. */
500 extern regexp *regcomp(char* text)
510 /* prepare for error handling */
512 if (setjmp(errorhandler))
521 /* if an empty regexp string was given, use the previous one */
526 FAIL("No previous RE");
530 else /* non-empty regexp given, so remember it */
534 previous = (char *)malloc((unsigned)(strlen(text) + 1));
536 strcpy(previous, text);
539 /* allocate memory */
544 size = calcsize(text) + sizeof(regexp);
545 re = (regexp *)malloc((unsigned)size);
549 FAIL("Not enough memory for this RE");
553 build = &re->program[1 + 32 * class_cnt];
554 re->program[0] = class_cnt;
555 for (token = 0; token < NSUBEXP; token++)
557 re->startp[token] = re->endp[token] = (char *)0;
567 for (token = M_START(0), peek = gettoken(&text, re);
569 token = peek, peek = gettoken(&text, re))
571 /* special processing for the closure operator */
572 if (IS_CLOSURE(peek))
574 /* detect misuse of closure operator */
577 FAIL("* or \\+ or \\? follows nothing");
579 else if (IS_META(token) && token != M_ANY && !IS_CLASS(token))
581 FAIL("* or \\+ or \\? can only follow a normal character or . or []");
584 /* it is okay -- make it prefix instead of postfix */
585 ADD_META(build, peek);
587 /* take care of "needfirst" - is this the first char? */
588 if (needfirst && peek == M_PLUS && !IS_META(token))
594 /* we used "peek" -- need to refill it */
595 peek = gettoken(&text, re);
596 if (IS_CLOSURE(peek))
598 FAIL("* or \\+ or \\? doubled up");
601 else if (!IS_META(token))
603 /* normal char is NOT argument of closure */
611 else if (token == M_ANY || IS_CLASS(token))
613 /* . or [] is NOT argument of closure */
618 /* the "token" character is not closure -- process it normally */
619 if (token == M_BEGLINE)
621 /* set the BOL flag instead of storing M_BEGLINE */
624 else if (IS_META(token))
626 ADD_META(build, token);
634 /* end it with a \) which MUST MATCH the opening \( */
635 ADD_META(build, M_END(0));
638 FAIL("Not enough \\)s");
647 /* This function searches through a string for text that matches an RE. */
648 /* re -- the compiled regexp to search for */
649 /* str -- the string to search through */
650 /* bol -- does str start at the beginning of a line? (boolean) */
651 /* ignoreCase -- ignoreCase or not */
652 extern int regexec(struct regexp* re, char* str, int bol, int ignoreCase)
654 char *prog; /* the entry point of re->program */
655 int len; /* length of the string */
658 /* if must start at the beginning of a line, and this isn't, then fail */
659 if (re->bol && bol==TRUE)
665 prog = re->program + 1 + 32 * re->program[0];
667 /* search for the RE in the string */
670 /* must occur at BOL */
672 && match1(re, *(char *)str, re->first, ignoreCase))/* wrong first letter? */
673 || len < re->minlen /* not long enough? */
674 || match(re, (char *)str, prog, str, ignoreCase)) /* doesn't match? */
675 return FALSE; /* THEN FAIL! */
677 else if (ignoreCase == FALSE)
679 /* can occur anywhere in the line, noignorecase */
680 for (here = (char *)str;
681 (re->first && re->first != *here)
682 || match(re, (char *)str, prog, here, ignoreCase);
685 if (len < re->minlen)
691 /* can occur anywhere in the line, ignorecase */
692 for (here = (char *)str;
693 (re->first && match1(re, *here, (int)re->first, ignoreCase))
694 || match(re, (char *)str, prog, here, ignoreCase);
697 if (len < re->minlen)
702 /* if we didn't fail, then we must have succeeded */
710 /* This performs substitutions after a regexp match has been found. */
711 extern void regsub(regexp* re, char* src, char* dst)
722 while ((c = *src++) != '\0')
724 /* recognize any meta characters */
734 end = cpy + strlen(cpy);
752 /* \0 thru \9 mean "copy subexpression" */
754 cpy = re->startp[(int)c];
755 end = re->endp[(int)c];
761 /* \U and \L mean "convert to upper/lowercase" */
767 /* \E ends the \U or \L */
771 /* "\&" means "original text" */
776 /* "\~" means "previous text, if any" */
780 /* ordinary char preceded by backslash */
787 /* ordinary character, so just copy it */
792 /* Note: to reach this point in the code, we must have evaded
793 * all "continue" statements. To do that, we must have hit
794 * a metacharacter that involves copying.
797 /* if there is nothing to copy, loop */
801 /* copy over a portion of the original */
808 /* convert to uppercase */
809 if (isascii(*cpy) && islower(*cpy))
811 *dst++ = toupper(*cpy);
822 /* convert to lowercase */
823 if (isascii(*cpy) && isupper(*cpy))
825 *dst++ = tolower(*cpy);
835 /* copy without any conversion */
839 /* \u and \l end automatically after the first char */
840 if (mod && (mod == 'u' || mod == 'l'))
848 /* remember what text we inserted this time */
851 previous1 = (char *)malloc((unsigned)(strlen(start) + 1));
853 strcpy(previous1, start);
857 #endif /* BB_REGEXP */