1 /* vi: set sw=4 ts=4: */
3 * Mini grep implementation for busybox using libc regex.
5 * Copyright (C) 1999,2000,2001 by Lineo, inc. and Mark Whitley
6 * Copyright (C) 1999,2000,2001 by Mark Whitley <markw@codepoet.org>
8 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
10 /* BB_AUDIT SUSv3 defects - unsupported option -x "match whole line only". */
11 /* BB_AUDIT GNU defects - always acts as -a. */
12 /* http://www.opengroup.org/onlinepubs/007904975/utilities/grep.html */
14 * 2004,2006 (C) Vladimir Oleynik <dzo@simtreas.ru> -
15 * correction "-e pattern1 -e pattern2" logic and more optimizations.
19 * (C) 2006 Jac Goudsmit added -o option
27 "lnqvscFiHhe:f:Lorm:" \
28 USE_FEATURE_GREP_CONTEXT("A:B:C:") \
29 USE_FEATURE_GREP_EGREP_ALIAS("E") \
31 USE_EXTRA_COMPAT("z") \
34 /* ignored: -a "assume all files to be text" */
35 /* ignored: -I "assume binary files have no matches" */
38 OPTBIT_l, /* list matched file names only */
39 OPTBIT_n, /* print line# */
40 OPTBIT_q, /* quiet - exit(EXIT_SUCCESS) of first match */
41 OPTBIT_v, /* invert the match, to select non-matching lines */
42 OPTBIT_s, /* suppress errors about file open errors */
43 OPTBIT_c, /* count matches per file (suppresses normal output) */
44 OPTBIT_F, /* literal match */
45 OPTBIT_i, /* case-insensitive */
46 OPTBIT_H, /* force filename display */
47 OPTBIT_h, /* inhibit filename display */
48 OPTBIT_e, /* -e PATTERN */
49 OPTBIT_f, /* -f FILE_WITH_PATTERNS */
50 OPTBIT_L, /* list unmatched file names only */
51 OPTBIT_o, /* show only matching parts of lines */
52 OPTBIT_r, /* recurse dirs */
53 OPTBIT_m, /* -m MAX_MATCHES */
54 USE_FEATURE_GREP_CONTEXT( OPTBIT_A ,) /* -A NUM: after-match context */
55 USE_FEATURE_GREP_CONTEXT( OPTBIT_B ,) /* -B NUM: before-match context */
56 USE_FEATURE_GREP_CONTEXT( OPTBIT_C ,) /* -C NUM: -A and -B combined */
57 USE_FEATURE_GREP_EGREP_ALIAS(OPTBIT_E ,) /* extended regexp */
58 USE_DESKTOP( OPTBIT_w ,) /* whole word match */
59 USE_EXTRA_COMPAT( OPTBIT_z ,) /* input is NUL terminated */
60 OPT_l = 1 << OPTBIT_l,
61 OPT_n = 1 << OPTBIT_n,
62 OPT_q = 1 << OPTBIT_q,
63 OPT_v = 1 << OPTBIT_v,
64 OPT_s = 1 << OPTBIT_s,
65 OPT_c = 1 << OPTBIT_c,
66 OPT_F = 1 << OPTBIT_F,
67 OPT_i = 1 << OPTBIT_i,
68 OPT_H = 1 << OPTBIT_H,
69 OPT_h = 1 << OPTBIT_h,
70 OPT_e = 1 << OPTBIT_e,
71 OPT_f = 1 << OPTBIT_f,
72 OPT_L = 1 << OPTBIT_L,
73 OPT_o = 1 << OPTBIT_o,
74 OPT_r = 1 << OPTBIT_r,
75 OPT_m = 1 << OPTBIT_m,
76 OPT_A = USE_FEATURE_GREP_CONTEXT( (1 << OPTBIT_A)) + 0,
77 OPT_B = USE_FEATURE_GREP_CONTEXT( (1 << OPTBIT_B)) + 0,
78 OPT_C = USE_FEATURE_GREP_CONTEXT( (1 << OPTBIT_C)) + 0,
79 OPT_E = USE_FEATURE_GREP_EGREP_ALIAS((1 << OPTBIT_E)) + 0,
80 OPT_w = USE_DESKTOP( (1 << OPTBIT_w)) + 0,
81 OPT_z = USE_EXTRA_COMPAT( (1 << OPTBIT_z)) + 0,
84 #define PRINT_FILES_WITH_MATCHES (option_mask32 & OPT_l)
85 #define PRINT_LINE_NUM (option_mask32 & OPT_n)
86 #define BE_QUIET (option_mask32 & OPT_q)
87 #define SUPPRESS_ERR_MSGS (option_mask32 & OPT_s)
88 #define PRINT_MATCH_COUNTS (option_mask32 & OPT_c)
89 #define FGREP_FLAG (option_mask32 & OPT_F)
90 #define PRINT_FILES_WITHOUT_MATCHES (option_mask32 & OPT_L)
91 #define NUL_DELIMITED (option_mask32 & OPT_z)
95 #if !ENABLE_EXTRA_COMPAT
98 RE_TRANSLATE_TYPE case_fold; /* RE_TRANSLATE_TYPE is [[un]signed] char* */
100 smalluint invert_search;
101 smalluint print_filename;
102 smalluint open_errors;
103 #if ENABLE_FEATURE_GREP_CONTEXT
104 smalluint did_print_line;
108 USE_EXTRA_COMPAT(size_t *before_buf_size;)
109 int last_line_printed;
111 /* globals used internally */
112 llist_t *pattern_head; /* growable list of patterns to match */
113 const char *cur_file; /* the current file we are reading */
115 #define G (*(struct globals*)&bb_common_bufsiz1)
116 #define INIT_G() do { \
117 struct G_sizecheck { \
118 char G_sizecheck[sizeof(G) > COMMON_BUFSIZE ? -1 : 1]; \
121 #define max_matches (G.max_matches )
122 #if !ENABLE_EXTRA_COMPAT
123 #define reflags (G.reflags )
125 #define case_fold (G.case_fold )
126 /* http://www.delorie.com/gnu/docs/regex/regex_46.html */
127 #define reflags re_syntax_options
131 #define REG_NOSUB bug:is:here /* should not be used */
132 #define REG_EXTENDED RE_SYNTAX_EGREP
133 #define REG_ICASE bug:is:here /* should not be used */
135 #define invert_search (G.invert_search )
136 #define print_filename (G.print_filename )
137 #define open_errors (G.open_errors )
138 #define did_print_line (G.did_print_line )
139 #define lines_before (G.lines_before )
140 #define lines_after (G.lines_after )
141 #define before_buf (G.before_buf )
142 #define before_buf_size (G.before_buf_size )
143 #define last_line_printed (G.last_line_printed )
144 #define pattern_head (G.pattern_head )
145 #define cur_file (G.cur_file )
148 typedef struct grep_list_data_t {
150 /* for GNU regex, matched_range must be persistent across grep_file() calls */
151 #if !ENABLE_EXTRA_COMPAT
152 regex_t compiled_regex;
153 regmatch_t matched_range;
155 struct re_pattern_buffer compiled_regex;
156 struct re_registers matched_range;
160 int flg_mem_alocated_compiled;
163 #if !ENABLE_EXTRA_COMPAT
164 #define print_line(line, line_len, linenum, decoration) \
165 print_line(line, linenum, decoration)
167 static void print_line(const char *line, size_t line_len, int linenum, char decoration)
169 #if ENABLE_FEATURE_GREP_CONTEXT
170 /* Happens when we go to next file, immediately hit match
171 * and try to print prev context... from prev file! Don't do it */
174 /* possibly print the little '--' separator */
175 if ((lines_before || lines_after) && did_print_line
176 && last_line_printed != linenum - 1
180 /* guard against printing "--" before first line of first file */
182 last_line_printed = linenum;
185 printf("%s%c", cur_file, decoration);
187 printf("%i%c", linenum, decoration);
188 /* Emulate weird GNU grep behavior with -ov */
189 if ((option_mask32 & (OPT_v|OPT_o)) != (OPT_v|OPT_o)) {
190 #if !ENABLE_EXTRA_COMPAT
193 fwrite(line, 1, line_len, stdout);
194 putchar(NUL_DELIMITED ? '\0' : '\n');
199 #if ENABLE_EXTRA_COMPAT
200 /* Unlike getline, this one removes trailing '\n' */
201 static ssize_t FAST_FUNC bb_getline(char **line_ptr, size_t *line_alloc_len, FILE *file)
205 int delim = (NUL_DELIMITED ? '\0' : '\n');
207 res_sz = getdelim(line_ptr, line_alloc_len, delim, file);
211 if (line[res_sz - 1] == delim)
212 line[--res_sz] = '\0';
214 free(line); /* uclibc allocates a buffer even on EOF. WTF? */
220 static int grep_file(FILE *file)
225 #if !ENABLE_EXTRA_COMPAT
230 size_t line_alloc_len;
231 #define rm_so start[0]
234 #if ENABLE_FEATURE_GREP_CONTEXT
235 int print_n_lines_after = 0;
236 int curpos = 0; /* track where we are in the circular 'before' buffer */
237 int idx = 0; /* used for iteration through the circular buffer */
239 enum { print_n_lines_after = 0 };
240 #endif /* ENABLE_FEATURE_GREP_CONTEXT */
243 #if !ENABLE_EXTRA_COMPAT
244 (line = xmalloc_fgetline(file)) != NULL
246 (line_len = bb_getline(&line, &line_alloc_len, file)) >= 0
249 llist_t *pattern_ptr = pattern_head;
250 grep_list_data_t *gl = gl; /* for gcc */
254 while (pattern_ptr) {
255 gl = (grep_list_data_t *)pattern_ptr->data;
257 found |= (strstr(line, gl->pattern) != NULL);
259 if (!(gl->flg_mem_alocated_compiled & COMPILED)) {
260 gl->flg_mem_alocated_compiled |= COMPILED;
261 #if !ENABLE_EXTRA_COMPAT
262 xregcomp(&gl->compiled_regex, gl->pattern, reflags);
264 memset(&gl->compiled_regex, 0, sizeof(gl->compiled_regex));
265 gl->compiled_regex.translate = case_fold; /* for -i */
266 if (re_compile_pattern(gl->pattern, strlen(gl->pattern), &gl->compiled_regex))
267 bb_error_msg_and_die("bad regex '%s'", gl->pattern);
270 #if !ENABLE_EXTRA_COMPAT
271 gl->matched_range.rm_so = 0;
272 gl->matched_range.rm_eo = 0;
275 #if !ENABLE_EXTRA_COMPAT
276 regexec(&gl->compiled_regex, line, 1, &gl->matched_range, 0) == 0
278 re_search(&gl->compiled_regex, line, line_len,
279 /*start:*/ 0, /*range:*/ line_len,
280 &gl->matched_range) >= 0
283 if (!(option_mask32 & OPT_w))
287 if (gl->matched_range.rm_so)
288 c = line[gl->matched_range.rm_so - 1];
289 if (!isalnum(c) && c != '_') {
290 c = line[gl->matched_range.rm_eo];
291 if (!c || (!isalnum(c) && c != '_'))
297 /* If it's non-inverted search, we can stop
299 if (found && !invert_search)
301 pattern_ptr = pattern_ptr->link;
302 } /* while (pattern_ptr) */
304 if (found ^ invert_search) {
306 /* keep track of matches */
309 /* quiet/print (non)matching file names only? */
310 if (option_mask32 & (OPT_q|OPT_l|OPT_L)) {
311 free(line); /* we don't need line anymore */
313 /* manpage says about -q:
314 * "exit immediately with zero status
315 * if any match is found,
316 * even if errors were detected" */
319 /* if we're just printing filenames, we stop after the first match */
320 if (PRINT_FILES_WITH_MATCHES) {
322 /* fall through to "return 1" */
324 /* OPT_L aka PRINT_FILES_WITHOUT_MATCHES: return early */
325 return 1; /* one match */
328 #if ENABLE_FEATURE_GREP_CONTEXT
329 /* Were we printing context and saw next (unwanted) match? */
330 if ((option_mask32 & OPT_m) && nmatches > max_matches)
334 /* print the matched line */
335 if (PRINT_MATCH_COUNTS == 0) {
336 #if ENABLE_FEATURE_GREP_CONTEXT
337 int prevpos = (curpos == 0) ? lines_before - 1 : curpos - 1;
339 /* if we were told to print 'before' lines and there is at least
340 * one line in the circular buffer, print them */
341 if (lines_before && before_buf[prevpos] != NULL) {
342 int first_buf_entry_line_num = linenum - lines_before;
344 /* advance to the first entry in the circular buffer, and
345 * figure out the line number is of the first line in the
348 while (before_buf[idx] == NULL) {
349 idx = (idx + 1) % lines_before;
350 first_buf_entry_line_num++;
353 /* now print each line in the buffer, clearing them as we go */
354 while (before_buf[idx] != NULL) {
355 print_line(before_buf[idx], before_buf_size[idx], first_buf_entry_line_num, '-');
356 free(before_buf[idx]);
357 before_buf[idx] = NULL;
358 idx = (idx + 1) % lines_before;
359 first_buf_entry_line_num++;
363 /* make a note that we need to print 'after' lines */
364 print_n_lines_after = lines_after;
366 if (option_mask32 & OPT_o) {
368 /* -Fo just prints the pattern
369 * (unless -v: -Fov doesnt print anything at all) */
371 print_line(gl->pattern, strlen(gl->pattern), linenum, ':');
373 char old = line[gl->matched_range.rm_eo];
374 line[gl->matched_range.rm_eo] = '\0';
375 print_line(line + gl->matched_range.rm_so,
376 gl->matched_range.rm_eo - gl->matched_range.rm_so,
378 line[gl->matched_range.rm_eo] = old;
379 #if !ENABLE_EXTRA_COMPAT
382 if (re_search(&gl->compiled_regex, line, line_len,
383 gl->matched_range.rm_eo, line_len - gl->matched_range.rm_eo,
384 &gl->matched_range) < 0)
389 print_line(line, line_len, linenum, ':');
393 #if ENABLE_FEATURE_GREP_CONTEXT
394 else { /* no match */
395 /* if we need to print some context lines after the last match, do so */
396 if (print_n_lines_after) {
397 print_line(line, strlen(line), linenum, '-');
398 print_n_lines_after--;
399 } else if (lines_before) {
400 /* Add the line to the circular 'before' buffer */
401 free(before_buf[curpos]);
402 before_buf[curpos] = line;
403 USE_EXTRA_COMPAT(before_buf_size[curpos] = line_len;)
404 curpos = (curpos + 1) % lines_before;
405 /* avoid free(line) - we took the line */
410 #endif /* ENABLE_FEATURE_GREP_CONTEXT */
411 #if !ENABLE_EXTRA_COMPAT
414 /* Did we print all context after last requested match? */
415 if ((option_mask32 & OPT_m)
416 && !print_n_lines_after
417 && nmatches == max_matches
421 } /* while (read line) */
423 /* special-case file post-processing for options where we don't print line
424 * matches, just filenames and possibly match counts */
426 /* grep -c: print [filename:]count, even if count is zero */
427 if (PRINT_MATCH_COUNTS) {
429 printf("%s:", cur_file);
430 printf("%d\n", nmatches);
433 /* grep -L: print just the filename */
434 if (PRINT_FILES_WITHOUT_MATCHES) {
435 /* nmatches is zero, no need to check it:
436 * we return 1 early if we detected a match
437 * and PRINT_FILES_WITHOUT_MATCHES is set */
444 #if ENABLE_FEATURE_CLEAN_UP
445 #define new_grep_list_data(p, m) add_grep_list_data(p, m)
446 static char *add_grep_list_data(char *pattern, int flg_used_mem)
448 #define new_grep_list_data(p, m) add_grep_list_data(p)
449 static char *add_grep_list_data(char *pattern)
452 grep_list_data_t *gl = xzalloc(sizeof(*gl));
453 gl->pattern = pattern;
454 #if ENABLE_FEATURE_CLEAN_UP
455 gl->flg_mem_alocated_compiled = flg_used_mem;
457 /*gl->flg_mem_alocated_compiled = 0;*/
462 static void load_regexes_from_file(llist_t *fopt)
469 char *ffile = cur->data;
473 f = xfopen_stdin(ffile);
474 while ((line = xmalloc_fgetline(f)) != NULL) {
475 llist_add_to(&pattern_head,
476 new_grep_list_data(line, ALLOCATED));
481 static int FAST_FUNC file_action_grep(const char *filename,
482 struct stat *statbuf UNUSED_PARAM,
484 int depth UNUSED_PARAM)
486 FILE *file = fopen_for_read(filename);
488 if (!SUPPRESS_ERR_MSGS)
489 bb_simple_perror_msg(filename);
494 *(int*)matched += grep_file(file);
499 static int grep_dir(const char *dir)
502 recursive_action(dir,
503 /* recurse=yes */ ACTION_RECURSE |
505 /* depthFirst=yes */ ACTION_DEPTHFIRST,
506 /* fileAction= */ file_action_grep,
507 /* dirAction= */ NULL,
508 /* userData= */ &matched,
513 int grep_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
514 int grep_main(int argc, char **argv)
518 llist_t *fopt = NULL;
520 /* do normal option parsing */
521 #if ENABLE_FEATURE_GREP_CONTEXT
524 /* -H unsets -h; -C unsets -A,-B; -e,-f are lists;
525 * -m,-A,-B,-C have numeric param */
526 opt_complementary = "H-h:C-AB:e::f::m+:A+:B+:C+";
529 &pattern_head, &fopt, &max_matches,
530 &lines_after, &lines_before, &Copt);
532 if (option_mask32 & OPT_C) {
533 /* -C unsets prev -A and -B, but following -A or -B
535 if (!(option_mask32 & OPT_A)) /* not overridden */
537 if (!(option_mask32 & OPT_B)) /* not overridden */
541 if (option_mask32 & (OPT_c|OPT_q|OPT_l|OPT_L)) {
542 option_mask32 &= ~OPT_n;
545 } else if (lines_before > 0) {
546 before_buf = xzalloc(lines_before * sizeof(before_buf[0]));
547 USE_EXTRA_COMPAT(before_buf_size = xzalloc(lines_before * sizeof(before_buf_size[0]));)
550 /* with auto sanity checks */
551 /* -H unsets -h; -c,-q or -l unset -n; -e,-f are lists; -m N */
552 opt_complementary = "H-h:c-n:q-n:l-n:e::f::m+";
553 getopt32(argv, OPTSTR_GREP,
554 &pattern_head, &fopt, &max_matches);
556 invert_search = ((option_mask32 & OPT_v) != 0); /* 0 | 1 */
558 if (pattern_head != NULL) {
559 /* convert char **argv to grep_list_data_t */
562 for (cur = pattern_head; cur; cur = cur->link)
563 cur->data = new_grep_list_data(cur->data, 0);
565 if (option_mask32 & OPT_f)
566 load_regexes_from_file(fopt);
568 if (ENABLE_FEATURE_GREP_FGREP_ALIAS && applet_name[0] == 'f')
569 option_mask32 |= OPT_F;
571 #if !ENABLE_EXTRA_COMPAT
572 if (!(option_mask32 & (OPT_o | OPT_w)))
576 if (ENABLE_FEATURE_GREP_EGREP_ALIAS
577 && (applet_name[0] == 'e' || (option_mask32 & OPT_E))
579 reflags |= REG_EXTENDED;
581 #if ENABLE_EXTRA_COMPAT
583 reflags = RE_SYNTAX_GREP;
587 if (option_mask32 & OPT_i) {
588 #if !ENABLE_EXTRA_COMPAT
589 reflags |= REG_ICASE;
592 case_fold = xmalloc(256);
593 for (i = 0; i < 256; i++)
594 case_fold[i] = (unsigned char)i;
595 for (i = 'a'; i <= 'z'; i++)
596 case_fold[i] = (unsigned char)(i - ('a' - 'A'));
603 /* if we didn't get a pattern from -e and no command file was specified,
604 * first parameter should be the pattern. no pattern, no worky */
605 if (pattern_head == NULL) {
609 pattern = new_grep_list_data(*argv++, 0);
610 llist_add_to(&pattern_head, pattern);
614 /* argv[0..(argc-1)] should be names of file to grep through. If
615 * there is more than one file to grep, we will print the filenames. */
618 /* -H / -h of course override */
619 if (option_mask32 & OPT_H)
621 if (option_mask32 & OPT_h)
624 /* If no files were specified, or '-' was specified, take input from
625 * stdin. Otherwise, we grep through all the files specified. */
630 if (!cur_file || LONE_DASH(cur_file)) {
631 cur_file = "(standard input)";
633 if (option_mask32 & OPT_r) {
635 if (stat(cur_file, &st) == 0 && S_ISDIR(st.st_mode)) {
636 if (!(option_mask32 & OPT_h))
638 matched += grep_dir(cur_file);
642 /* else: fopen(dir) will succeed, but reading won't */
643 file = fopen_for_read(cur_file);
645 if (!SUPPRESS_ERR_MSGS)
646 bb_simple_perror_msg(cur_file);
651 matched += grep_file(file);
652 fclose_if_not_stdin(file);
654 } while (--argc > 0);
656 /* destroy all the elments in the pattern list */
657 if (ENABLE_FEATURE_CLEAN_UP) {
658 while (pattern_head) {
659 llist_t *pattern_head_ptr = pattern_head;
660 grep_list_data_t *gl = (grep_list_data_t *)pattern_head_ptr->data;
662 pattern_head = pattern_head->link;
663 if (gl->flg_mem_alocated_compiled & ALLOCATED)
665 if (gl->flg_mem_alocated_compiled & COMPILED)
666 regfree(&gl->compiled_regex);
668 free(pattern_head_ptr);
671 /* 0 = success, 1 = failed, 2 = error */
674 return !matched; /* invert return value: 0 = success, 1 = failed */