blob: b264ffb6fd3bba6c91736ec4a6fe26fe29e6fafc [file] [log] [blame]
Eric Andersenaa0765e1999-10-22 04:30:20 +00001/* regexp.c */
2
3#include "internal.h"
4#include "regexp.h"
5#include <setjmp.h>
6#include <stdio.h>
7#include <ctype.h>
8
9
Eric Andersenb186d981999-12-03 09:19:54 +000010#if ( defined BB_GREP || defined BB_SED)
Eric Andersenaa0765e1999-10-22 04:30:20 +000011
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...
16 * -Erik Andersen
17 */
18extern int find_match(char *haystack, char *needle, int ignoreCase)
19{
20 int status;
21 struct regexp* re;
22 re = regcomp( needle);
23 status = regexec(re, haystack, FALSE, ignoreCase);
24 free( re);
25 return( status);
26}
27
Eric Andersen7f1acfd1999-10-29 23:09:13 +000028#if defined BB_SED
Eric Andersenc1525e81999-10-29 00:07:31 +000029/* 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. */
Eric Andersen7f1acfd1999-10-29 23:09:13 +000031extern int replace_match(char *haystack, char *needle, char *newNeedle, int ignoreCase)
Eric Andersenc1525e81999-10-29 00:07:31 +000032{
33 int status;
Eric Andersenc1525e81999-10-29 00:07:31 +000034 struct regexp* re;
Eric Andersen7f1acfd1999-10-29 23:09:13 +000035 char *s, buf[BUF_SIZE], *d = buf;
36
Eric Andersenc1525e81999-10-29 00:07:31 +000037 re = regcomp( needle);
38 status = regexec(re, haystack, FALSE, ignoreCase);
Eric Andersen7f1acfd1999-10-29 23:09:13 +000039 if (status==TRUE) {
40 s=haystack;
Eric Andersenc1525e81999-10-29 00:07:31 +000041
Eric Andersen7f1acfd1999-10-29 23:09:13 +000042 do {
43 /* copy stuff from before the match */
44 while (s < re->startp[0])
45 *d++ = *s++;
46 /* substitute for the matched part */
47 regsub(re, newNeedle, d);
48 s = re->endp[0];
49 d += strlen(d);
50 } while (regexec(re, s, FALSE, ignoreCase) == TRUE);
51 /* copy stuff from after the match */
52 while ( (*d++ = *s++) ) {}
Eric Andersen7f1acfd1999-10-29 23:09:13 +000053 d[0] = '\0';
54 strcpy(haystack, buf);
55 }
Eric Andersenc1525e81999-10-29 00:07:31 +000056 free( re);
57 return( status);
58}
Eric Andersen7f1acfd1999-10-29 23:09:13 +000059#endif
Eric Andersenc1525e81999-10-29 00:07:31 +000060
Eric Andersenaa0765e1999-10-22 04:30:20 +000061
62/* code swiped from elvis-tiny 1.4 (a clone of vi) and adjusted to
63 * suit the needs of busybox by Erik Andersen.
64 *
65 * From the README:
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>
69 *
70 *
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 *.
84 *
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
89 * (32 bytes) long.
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.
95 *
96 */
97
98
99
100static char *previous; /* the previous regexp, used when null regexp is given */
Eric Andersenabc0f4f1999-12-08 23:19:36 +0000101#if defined BB_SED
Eric Andersenaa0765e1999-10-22 04:30:20 +0000102static char *previous1; /* a copy of the text from the previous substitution for regsub()*/
Eric Andersenabc0f4f1999-12-08 23:19:36 +0000103#endif
Eric Andersenaa0765e1999-10-22 04:30:20 +0000104
105
106/* These are used to classify or recognize meta-characters */
107#define META '\0'
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)
117
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 \) */
130
131/* These are used during compilation */
132static int class_cnt; /* used to assign class IDs */
133static int start_cnt; /* used to assign start IDs */
134static int end_stk[NSUBEXP];/* used to assign end IDs */
135static int end_sp;
136static char *retext; /* points to the text being compiled */
137
138/* error-handling stuff */
139jmp_buf errorhandler;
Eric Andersenb6a44b81999-11-13 04:47:09 +0000140#define FAIL(why) do {fprintf(stderr, why); longjmp(errorhandler, 1);} while (0)
Eric Andersenaa0765e1999-10-22 04:30:20 +0000141
142
143
144
145/* This function builds a bitmap for a particular class */
146/* text -- start of the class */
147/* bmap -- the bitmap */
148static char *makeclass(char* text, char* bmap)
149{
150 int i;
151 int complement = 0;
152
153
154 /* zero the bitmap */
155 for (i = 0; bmap && i < 32; i++)
156 {
157 bmap[i] = 0;
158 }
159
160 /* see if we're going to complement this class */
161 if (*text == '^')
162 {
163 text++;
164 complement = 1;
165 }
166
167 /* add in the characters */
168 while (*text && *text != ']')
169 {
170 /* is this a span of characters? */
171 if (text[1] == '-' && text[2])
172 {
173 /* spans can't be backwards */
174 if (text[0] > text[2])
175 {
176 FAIL("Backwards span in []");
177 }
178
179 /* add each character in the span to the bitmap */
180 for (i = text[0]; bmap && i <= text[2]; i++)
181 {
182 bmap[i >> 3] |= (1 << (i & 7));
183 }
184
185 /* move past this span */
186 text += 3;
187 }
188 else
189 {
190 /* add this single character to the span */
191 i = *text++;
192 if (bmap)
193 {
194 bmap[i >> 3] |= (1 << (i & 7));
195 }
196 }
197 }
198
199 /* make sure the closing ] is missing */
200 if (*text++ != ']')
201 {
202 FAIL("] missing");
203 }
204
205 /* if we're supposed to complement this class, then do so */
206 if (complement && bmap)
207 {
208 for (i = 0; i < 32; i++)
209 {
210 bmap[i] = ~bmap[i];
211 }
212 }
213
214 return text;
215}
216
217
218
219
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.
224 */
225static int gettoken(sptr, re)
226 char **sptr;
227 regexp *re;
228{
229 int c;
230
231 c = **sptr;
232 ++*sptr;
233 if (c == '\\')
234 {
235 c = **sptr;
236 ++*sptr;
237 switch (c)
238 {
239 case '<':
240 return M_BEGWORD;
241
242 case '>':
243 return M_ENDWORD;
244
245 case '(':
246 if (start_cnt >= NSUBEXP)
247 {
248 FAIL("Too many \\(s");
249 }
250 end_stk[end_sp++] = start_cnt;
251 return M_START(start_cnt++);
252
253 case ')':
254 if (end_sp <= 0)
255 {
256 FAIL("Mismatched \\)");
257 }
258 return M_END(end_stk[--end_sp]);
259
260 case '*':
261 return M_SPLAT;
262
263 case '.':
264 return M_ANY;
265
266 case '+':
267 return M_PLUS;
268
269 case '?':
270 return M_QMARK;
271
272 default:
273 return c;
274 }
275 }
276 else {
277 switch (c)
278 {
279 case '^':
280 if (*sptr == retext + 1)
281 {
282 return M_BEGLINE;
283 }
284 return c;
285
286 case '$':
287 if (!**sptr)
288 {
289 return M_ENDLINE;
290 }
291 return c;
292
293 case '.':
294 return M_ANY;
295
296 case '*':
297 return M_SPLAT;
298
299 case '[':
300 /* make sure we don't have too many classes */
301 if (class_cnt >= 10)
302 {
303 FAIL("Too many []s");
304 }
305
306 /* process the character list for this class */
307 if (re)
308 {
309 /* generate the bitmap for this class */
310 *sptr = makeclass(*sptr, re->program + 1 + 32 * class_cnt);
311 }
312 else
313 {
314 /* skip to end of the class */
315 *sptr = makeclass(*sptr, (char *)0);
316 }
317 return M_CLASS(class_cnt++);
318
319 default:
320 return c;
321 }
322 }
323 /*NOTREACHED*/
324}
325
326
327
328
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.
332 */
333static unsigned calcsize(text)
334 char *text;
335{
336 unsigned size;
337 int token;
338
339 retext = text;
340 class_cnt = 0;
341 start_cnt = 1;
342 end_sp = 0;
343 size = 5;
344 while ((token = gettoken(&text, (regexp *)0)) != 0)
345 {
346 if (IS_CLASS(token))
347 {
348 size += 34;
349 }
350 else if (IS_META(token))
351 {
352 size += 2;
353 }
354 else
355 {
356 size++;
357 }
358 }
359
360 return size;
361}
362
363
364
365/*---------------------------------------------------------------------------*/
366
367
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
370 * 1 if they don't.
371 */
372static int match1(regexp* re, char ch, int token, int ignoreCase)
373{
374 if (!ch)
375 {
376 /* the end of a line can't match any RE of width 1 */
377 return 1;
378 }
379 if (token == M_ANY)
380 {
381 return 0;
382 }
383 else if (IS_CLASS(token))
384 {
385 if (re->program[1 + 32 * (token - M_CLASS(0)) + (ch >> 3)] & (1 << (ch & 7)))
386 return 0;
387 }
388 else if (ch == token
389 || (ignoreCase==TRUE && isupper(ch) && tolower(ch) == token))
390 {
391 return 0;
392 }
393 return 1;
394}
395
396
397
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.
401 */
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 */
406static int match(regexp* re, char* str, char* prog, char* here, int ignoreCase)
407{
408 int token;
409 int nmatched;
410 int closure;
411
412 for (token = GET_META(prog); !IS_CLOSURE(token); prog++, token = GET_META(prog))
413 {
414 switch (token)
415 {
416 /*case M_BEGLINE: can't happen; re->bol is used instead */
417 case M_ENDLINE:
418 if (*here)
419 return 1;
420 break;
421
422 case M_BEGWORD:
423 if (here != str &&
424 (here[-1] == '_' ||
425 (isascii(here[-1]) && isalnum(here[-1]))))
426 return 1;
427 break;
428
429 case M_ENDWORD:
430 if ((here[0] == '_' || isascii(here[0])) && isalnum(here[0]))
431 return 1;
432 break;
433
434 case M_START(0):
435 case M_START(1):
436 case M_START(2):
437 case M_START(3):
438 case M_START(4):
439 case M_START(5):
440 case M_START(6):
441 case M_START(7):
442 case M_START(8):
443 case M_START(9):
444 re->startp[token - M_START(0)] = (char *)here;
445 break;
446
447 case M_END(0):
448 case M_END(1):
449 case M_END(2):
450 case M_END(3):
451 case M_END(4):
452 case M_END(5):
453 case M_END(6):
454 case M_END(7):
455 case M_END(8):
456 case M_END(9):
457 re->endp[token - M_END(0)] = (char *)here;
458 if (token == M_END(0))
459 {
460 return 0;
461 }
462 break;
463
464 default: /* literal, M_CLASS(n), or M_ANY */
465 if (match1(re, *here, token, ignoreCase) != 0)
466 return 1;
467 here++;
468 }
469 }
470
471 /* C L O S U R E */
472
473 /* step 1: see what we have to match against, and move "prog" to point
474 * the the remainder of the compiled RE.
475 */
476 closure = token;
477 prog++, token = GET_META(prog);
478 prog++;
479
480 /* step 2: see how many times we can match that token against the string */
481 for (nmatched = 0;
482 (closure != M_QMARK || nmatched < 1) && *here && match1(re, *here, token, ignoreCase) == 0;
483 nmatched++, here++)
484 {
485 }
486
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)
489 {
490 nmatched--;
491 here--;
492 }
493
494 /* so how did it work out? */
495 if (nmatched >= ((closure == M_PLUS) ? 1 : 0))
496 return 0;
497 return 1;
498}
499
500
501/* This function compiles a regexp. */
502extern regexp *regcomp(char* text)
503{
504 int needfirst;
505 unsigned size;
506 int token;
507 int peek;
508 char *build;
Eric Andersen96bcfd31999-11-12 01:30:18 +0000509 regexp *re; // Ignore compiler whining. If we longjmp, we don't use re anymore.
Eric Andersenaa0765e1999-10-22 04:30:20 +0000510
511
512 /* prepare for error handling */
513 re = (regexp *)0;
514 if (setjmp(errorhandler))
515 {
516 if (re)
517 {
518 free(re);
519 }
520 return (regexp *)0;
521 }
522
523 /* if an empty regexp string was given, use the previous one */
524 if (*text == 0)
525 {
526 if (!previous)
527 {
528 FAIL("No previous RE");
529 }
530 text = previous;
531 }
532 else /* non-empty regexp given, so remember it */
533 {
534 if (previous)
535 free(previous);
536 previous = (char *)malloc((unsigned)(strlen(text) + 1));
537 if (previous)
538 strcpy(previous, text);
539 }
540
541 /* allocate memory */
542 class_cnt = 0;
543 start_cnt = 1;
544 end_sp = 0;
545 retext = text;
546 size = calcsize(text) + sizeof(regexp);
547 re = (regexp *)malloc((unsigned)size);
548
549 if (!re)
550 {
551 FAIL("Not enough memory for this RE");
552 }
553
554 /* compile it */
555 build = &re->program[1 + 32 * class_cnt];
556 re->program[0] = class_cnt;
557 for (token = 0; token < NSUBEXP; token++)
558 {
559 re->startp[token] = re->endp[token] = (char *)0;
560 }
561 re->first = 0;
562 re->bol = 0;
563 re->minlen = 0;
564 needfirst = 1;
565 class_cnt = 0;
566 start_cnt = 1;
567 end_sp = 0;
568 retext = text;
569 for (token = M_START(0), peek = gettoken(&text, re);
570 token;
571 token = peek, peek = gettoken(&text, re))
572 {
573 /* special processing for the closure operator */
574 if (IS_CLOSURE(peek))
575 {
576 /* detect misuse of closure operator */
577 if (IS_START(token))
578 {
579 FAIL("* or \\+ or \\? follows nothing");
580 }
581 else if (IS_META(token) && token != M_ANY && !IS_CLASS(token))
582 {
583 FAIL("* or \\+ or \\? can only follow a normal character or . or []");
584 }
585
586 /* it is okay -- make it prefix instead of postfix */
587 ADD_META(build, peek);
588
589 /* take care of "needfirst" - is this the first char? */
590 if (needfirst && peek == M_PLUS && !IS_META(token))
591 {
592 re->first = token;
593 }
594 needfirst = 0;
595
596 /* we used "peek" -- need to refill it */
597 peek = gettoken(&text, re);
598 if (IS_CLOSURE(peek))
599 {
600 FAIL("* or \\+ or \\? doubled up");
601 }
602 }
603 else if (!IS_META(token))
604 {
605 /* normal char is NOT argument of closure */
606 if (needfirst)
607 {
608 re->first = token;
609 needfirst = 0;
610 }
611 re->minlen++;
612 }
613 else if (token == M_ANY || IS_CLASS(token))
614 {
615 /* . or [] is NOT argument of closure */
616 needfirst = 0;
617 re->minlen++;
618 }
619
620 /* the "token" character is not closure -- process it normally */
621 if (token == M_BEGLINE)
622 {
623 /* set the BOL flag instead of storing M_BEGLINE */
624 re->bol = 1;
625 }
626 else if (IS_META(token))
627 {
628 ADD_META(build, token);
629 }
630 else
631 {
632 *build++ = token;
633 }
634 }
635
636 /* end it with a \) which MUST MATCH the opening \( */
637 ADD_META(build, M_END(0));
638 if (end_sp > 0)
639 {
640 FAIL("Not enough \\)s");
641 }
642
643 return re;
644}
645
646
647
648
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 */
654extern int regexec(struct regexp* re, char* str, int bol, int ignoreCase)
655{
656 char *prog; /* the entry point of re->program */
657 int len; /* length of the string */
658 char *here;
659
660 /* if must start at the beginning of a line, and this isn't, then fail */
661 if (re->bol && bol==TRUE)
662 {
663 return FALSE;
664 }
665
666 len = strlen(str);
667 prog = re->program + 1 + 32 * re->program[0];
668
669 /* search for the RE in the string */
670 if (re->bol)
671 {
672 /* must occur at BOL */
673 if ((re->first
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! */
678 }
679 else if (ignoreCase == FALSE)
680 {
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);
685 here++, len--)
686 {
687 if (len < re->minlen)
688 return FALSE;
689 }
690 }
691 else
692 {
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);
697 here++, len--)
698 {
699 if (len < re->minlen)
700 return FALSE;
701 }
702 }
703
704 /* if we didn't fail, then we must have succeeded */
705 return TRUE;
706}
707
708
709
710
Eric Andersen7f1acfd1999-10-29 23:09:13 +0000711#if defined BB_SED
Eric Andersenaa0765e1999-10-22 04:30:20 +0000712/* This performs substitutions after a regexp match has been found. */
713extern void regsub(regexp* re, char* src, char* dst)
714{
715 char *cpy;
716 char *end;
717 char c;
718 char *start;
719 int mod;
720
721 mod = 0;
722
723 start = src;
724 while ((c = *src++) != '\0')
725 {
726 /* recognize any meta characters */
727 if (c == '&')
728 {
729 cpy = re->startp[0];
730 end = re->endp[0];
731 }
732 else if (c == '~')
733 {
734 cpy = previous1;
735 if (cpy)
736 end = cpy + strlen(cpy);
737 }
738 else
739 if (c == '\\')
740 {
741 c = *src++;
742 switch (c)
743 {
744 case '0':
745 case '1':
746 case '2':
747 case '3':
748 case '4':
749 case '5':
750 case '6':
751 case '7':
752 case '8':
753 case '9':
754 /* \0 thru \9 mean "copy subexpression" */
755 c -= '0';
756 cpy = re->startp[(int)c];
757 end = re->endp[(int)c];
758 break;
759 case 'U':
760 case 'u':
761 case 'L':
762 case 'l':
763 /* \U and \L mean "convert to upper/lowercase" */
764 mod = c;
765 continue;
766
767 case 'E':
768 case 'e':
769 /* \E ends the \U or \L */
770 mod = 0;
771 continue;
772 case '&':
773 /* "\&" means "original text" */
774 *dst++ = c;
775 continue;
776
777 case '~':
778 /* "\~" means "previous text, if any" */
779 *dst++ = c;
780 continue;
781 default:
782 /* ordinary char preceded by backslash */
783 *dst++ = c;
784 continue;
785 }
786 }
787 else
788 {
789 /* ordinary character, so just copy it */
790 *dst++ = c;
791 continue;
792 }
793
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.
797 */
798
799 /* if there is nothing to copy, loop */
800 if (!cpy)
801 continue;
802
803 /* copy over a portion of the original */
804 while (cpy < end)
805 {
806 switch (mod)
807 {
808 case 'U':
809 case 'u':
810 /* convert to uppercase */
811 if (isascii(*cpy) && islower(*cpy))
812 {
813 *dst++ = toupper(*cpy);
814 cpy++;
815 }
816 else
817 {
818 *dst++ = *cpy++;
819 }
820 break;
821
822 case 'L':
823 case 'l':
824 /* convert to lowercase */
825 if (isascii(*cpy) && isupper(*cpy))
826 {
827 *dst++ = tolower(*cpy);
828 cpy++;
829 }
830 else
831 {
832 *dst++ = *cpy++;
833 }
834 break;
835
836 default:
837 /* copy without any conversion */
838 *dst++ = *cpy++;
839 }
840
841 /* \u and \l end automatically after the first char */
842 if (mod && (mod == 'u' || mod == 'l'))
843 {
844 mod = 0;
845 }
846 }
847 }
848 *dst = '\0';
849
850 /* remember what text we inserted this time */
851 if (previous1)
852 free(previous1);
853 previous1 = (char *)malloc((unsigned)(strlen(start) + 1));
854 if (previous1)
855 strcpy(previous1, start);
856}
Eric Andersen7f1acfd1999-10-29 23:09:13 +0000857#endif
Eric Andersenaa0765e1999-10-22 04:30:20 +0000858
859#endif /* BB_REGEXP */
860
861