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. */
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
28 USE_FEATURE_GREP_CONTEXT("A:B:C:") \
29 USE_FEATURE_GREP_EGREP_ALIAS("E") \
48 USE_FEATURE_GREP_CONTEXT(OPTBIT_A ,)
49 USE_FEATURE_GREP_CONTEXT(OPTBIT_B ,)
50 USE_FEATURE_GREP_CONTEXT(OPTBIT_C ,)
51 USE_FEATURE_GREP_CONTEXT(OPTBIT_E ,)
52 USE_DESKTOP( OPTBIT_w ,)
53 OPT_l = 1 << OPTBIT_l,
54 OPT_n = 1 << OPTBIT_n,
55 OPT_q = 1 << OPTBIT_q,
56 OPT_v = 1 << OPTBIT_v,
57 OPT_s = 1 << OPTBIT_s,
58 OPT_c = 1 << OPTBIT_c,
59 OPT_F = 1 << OPTBIT_F,
60 OPT_i = 1 << OPTBIT_i,
61 OPT_H = 1 << OPTBIT_H,
62 OPT_h = 1 << OPTBIT_h,
63 OPT_e = 1 << OPTBIT_e,
64 OPT_f = 1 << OPTBIT_f,
65 OPT_L = 1 << OPTBIT_L,
66 OPT_o = 1 << OPTBIT_o,
67 OPT_r = 1 << OPTBIT_r,
68 OPT_A = USE_FEATURE_GREP_CONTEXT((1 << OPTBIT_A)) + 0,
69 OPT_B = USE_FEATURE_GREP_CONTEXT((1 << OPTBIT_B)) + 0,
70 OPT_C = USE_FEATURE_GREP_CONTEXT((1 << OPTBIT_C)) + 0,
71 OPT_E = USE_FEATURE_GREP_CONTEXT((1 << OPTBIT_E)) + 0,
72 OPT_w = USE_DESKTOP( (1 << OPTBIT_w)) + 0,
75 #define PRINT_FILES_WITH_MATCHES (option_mask32 & OPT_l)
76 #define PRINT_LINE_NUM (option_mask32 & OPT_n)
77 #define BE_QUIET (option_mask32 & OPT_q)
78 #define SUPPRESS_ERR_MSGS (option_mask32 & OPT_s)
79 #define PRINT_MATCH_COUNTS (option_mask32 & OPT_c)
80 #define FGREP_FLAG (option_mask32 & OPT_F)
81 #define PRINT_FILES_WITHOUT_MATCHES (option_mask32 & OPT_L)
83 typedef unsigned char byte_t;
86 static byte_t invert_search;
87 static byte_t print_filename;
88 static byte_t open_errors;
90 #if ENABLE_FEATURE_GREP_CONTEXT
91 static int lines_before;
92 static int lines_after;
93 static char **before_buf;
94 static int last_line_printed;
95 #endif /* ENABLE_FEATURE_GREP_CONTEXT */
97 /* globals used internally */
98 static llist_t *pattern_head; /* growable list of patterns to match */
99 static const char *cur_file; /* the current file we are reading */
101 typedef struct grep_list_data_t {
104 #define PATTERN_MEM_A 1
106 int flg_mem_alocated_compiled;
109 static void print_line(const char *line, int linenum, char decoration)
111 #if ENABLE_FEATURE_GREP_CONTEXT
112 /* possibly print the little '--' separator */
113 if ((lines_before || lines_after) && last_line_printed &&
114 last_line_printed < linenum - 1) {
117 last_line_printed = linenum;
120 printf("%s%c", cur_file, decoration);
122 printf("%i%c", linenum, decoration);
123 /* Emulate weird GNU grep behavior with -ov */
124 if ((option_mask32 & (OPT_v+OPT_o)) != (OPT_v+OPT_o))
128 static int grep_file(FILE *file)
135 #if ENABLE_FEATURE_GREP_CONTEXT
136 int print_n_lines_after = 0;
137 int curpos = 0; /* track where we are in the circular 'before' buffer */
138 int idx = 0; /* used for iteration through the circular buffer */
139 #endif /* ENABLE_FEATURE_GREP_CONTEXT */
141 while ((line = xmalloc_getline(file)) != NULL) {
142 llist_t *pattern_ptr = pattern_head;
143 grep_list_data_t * gl;
147 while (pattern_ptr) {
148 gl = (grep_list_data_t *)pattern_ptr->data;
150 ret = strstr(line, gl->pattern) != NULL;
153 * test for a postitive-assertion match (regexec returns success (0)
154 * and the user did not specify invert search), or a negative-assertion
155 * match (regexec returns failure (REG_NOMATCH) and the user specified
158 if (!(gl->flg_mem_alocated_compiled & COMPILED)) {
159 gl->flg_mem_alocated_compiled |= COMPILED;
160 xregcomp(&(gl->preg), gl->pattern, reflags);
164 if (regexec(&(gl->preg), line, 1, ®match, 0) == 0) {
165 if (!(option_mask32 & OPT_w))
170 c = line[regmatch.rm_so - 1];
171 if (!isalnum(c) && c != '_') {
172 c = line[regmatch.rm_eo];
173 if (!c || (!isalnum(c) && c != '_'))
179 pattern_ptr = pattern_ptr->link;
180 } /* while (pattern_ptr) */
182 if (ret ^ invert_search) {
183 if (PRINT_FILES_WITH_MATCHES || BE_QUIET)
186 /* if we found a match but were told to be quiet, stop here */
187 if (BE_QUIET || PRINT_FILES_WITHOUT_MATCHES)
190 /* keep track of matches */
193 /* if we're just printing filenames, we stop after the first match */
194 if (PRINT_FILES_WITH_MATCHES)
197 /* print the matched line */
198 if (PRINT_MATCH_COUNTS == 0) {
199 #if ENABLE_FEATURE_GREP_CONTEXT
200 int prevpos = (curpos == 0) ? lines_before - 1 : curpos - 1;
202 /* if we were told to print 'before' lines and there is at least
203 * one line in the circular buffer, print them */
204 if (lines_before && before_buf[prevpos] != NULL) {
205 int first_buf_entry_line_num = linenum - lines_before;
207 /* advance to the first entry in the circular buffer, and
208 * figure out the line number is of the first line in the
211 while (before_buf[idx] == NULL) {
212 idx = (idx + 1) % lines_before;
213 first_buf_entry_line_num++;
216 /* now print each line in the buffer, clearing them as we go */
217 while (before_buf[idx] != NULL) {
218 print_line(before_buf[idx], first_buf_entry_line_num, '-');
219 free(before_buf[idx]);
220 before_buf[idx] = NULL;
221 idx = (idx + 1) % lines_before;
222 first_buf_entry_line_num++;
226 /* make a note that we need to print 'after' lines */
227 print_n_lines_after = lines_after;
229 if (option_mask32 & OPT_o) {
230 line[regmatch.rm_eo] = '\0';
231 print_line(line + regmatch.rm_so, linenum, ':');
233 print_line(line, linenum, ':');
237 #if ENABLE_FEATURE_GREP_CONTEXT
238 else { /* no match */
239 /* Add the line to the circular 'before' buffer */
241 free(before_buf[curpos]);
242 before_buf[curpos] = xstrdup(line);
243 curpos = (curpos + 1) % lines_before;
247 /* if we need to print some context lines after the last match, do so */
248 if (print_n_lines_after && (last_line_printed != linenum)) {
249 print_line(line, linenum, '-');
250 print_n_lines_after--;
252 #endif /* ENABLE_FEATURE_GREP_CONTEXT */
256 /* special-case file post-processing for options where we don't print line
257 * matches, just filenames and possibly match counts */
259 /* grep -c: print [filename:]count, even if count is zero */
260 if (PRINT_MATCH_COUNTS) {
262 printf("%s:", cur_file);
263 printf("%d\n", nmatches);
266 /* grep -l: print just the filename, but only if we grepped the line in the file */
267 if (PRINT_FILES_WITH_MATCHES && nmatches > 0) {
271 /* grep -L: print just the filename, but only if we didn't grep the line in the file */
272 if (PRINT_FILES_WITHOUT_MATCHES && nmatches == 0) {
279 #if ENABLE_FEATURE_CLEAN_UP
280 #define new_grep_list_data(p, m) add_grep_list_data(p, m)
281 static char * add_grep_list_data(char *pattern, int flg_used_mem)
283 #define new_grep_list_data(p, m) add_grep_list_data(p)
284 static char * add_grep_list_data(char *pattern)
287 grep_list_data_t *gl = xmalloc(sizeof(grep_list_data_t));
288 gl->pattern = pattern;
289 #if ENABLE_FEATURE_CLEAN_UP
290 gl->flg_mem_alocated_compiled = flg_used_mem;
292 gl->flg_mem_alocated_compiled = 0;
298 static void load_regexes_from_file(llist_t *fopt)
305 char *ffile = cur->data;
309 f = xfopen(ffile, "r");
310 while ((line = xmalloc_getline(f)) != NULL) {
311 llist_add_to(&pattern_head,
312 new_grep_list_data(line, PATTERN_MEM_A));
317 static int file_action_grep(const char *filename, struct stat *statbuf, void* matched, int depth)
319 FILE *file = fopen(filename, "r");
321 if (!SUPPRESS_ERR_MSGS)
322 bb_perror_msg("%s", cur_file);
327 *(int*)matched += grep_file(file);
332 static int grep_dir(const char *dir)
335 recursive_action(dir,
337 /* followLinks= */ 0,
339 /* fileAction= */ file_action_grep,
340 /* dirAction= */ NULL,
341 /* userData= */ &matched,
346 int grep_main(int argc, char **argv);
347 int grep_main(int argc, char **argv)
351 llist_t *fopt = NULL;
353 /* do normal option parsing */
354 #if ENABLE_FEATURE_GREP_CONTEXT
359 opt_complementary = "H-h:e::f::C-AB";
362 &pattern_head, &fopt,
363 &slines_after, &slines_before, &Copt);
365 if (option_mask32 & OPT_C) {
366 /* -C unsets prev -A and -B, but following -A or -B
368 if (!(option_mask32 & OPT_A)) /* not overridden */
370 if (!(option_mask32 & OPT_B)) /* not overridden */
371 slines_before = Copt;
372 option_mask32 |= OPT_A|OPT_B; /* for parser */
374 if (option_mask32 & OPT_A) {
375 lines_after = xatoi_u(slines_after);
377 if (option_mask32 & OPT_B) {
378 lines_before = xatoi_u(slines_before);
381 if (option_mask32 & (OPT_c|OPT_q|OPT_l|OPT_L)) {
382 option_mask32 &= ~OPT_n;
385 } else if (lines_before > 0)
386 before_buf = xzalloc(lines_before * sizeof(char *));
388 /* with auto sanity checks */
389 opt_complementary = "H-h:e::f::c-n:q-n:l-n";
390 getopt32(argc, argv, OPTSTR_GREP,
391 &pattern_head, &fopt);
393 invert_search = ((option_mask32 & OPT_v) != 0); /* 0 | 1 */
395 if (pattern_head != NULL) {
396 /* convert char *argv[] to grep_list_data_t */
399 for (cur = pattern_head; cur; cur = cur->link)
400 cur->data = new_grep_list_data(cur->data, 0);
402 if (option_mask32 & OPT_f)
403 load_regexes_from_file(fopt);
405 if (ENABLE_FEATURE_GREP_FGREP_ALIAS && applet_name[0] == 'f')
406 option_mask32 |= OPT_F;
408 if (!(option_mask32 & (OPT_o | OPT_w)))
411 if (ENABLE_FEATURE_GREP_EGREP_ALIAS &&
412 (applet_name[0] == 'e' || (option_mask32 & OPT_E)))
413 reflags |= REG_EXTENDED;
415 if (option_mask32 & OPT_i)
416 reflags |= REG_ICASE;
421 /* if we didn't get a pattern from a -e and no command file was specified,
422 * argv[optind] should be the pattern. no pattern, no worky */
423 if (pattern_head == NULL) {
427 pattern = new_grep_list_data(*argv++, 0);
428 llist_add_to(&pattern_head, pattern);
432 /* argv[(optind)..(argc-1)] should be names of file to grep through. If
433 * there is more than one file to grep, we will print the filenames. */
436 /* -H / -h of course override */
437 if (option_mask32 & OPT_H)
439 if (option_mask32 & OPT_h)
442 /* If no files were specified, or '-' was specified, take input from
443 * stdin. Otherwise, we grep through all the files specified. */
450 if (!cur_file || (*cur_file == '-' && !cur_file[1])) {
451 cur_file = "(standard input)";
453 if (option_mask32 & OPT_r) {
455 if (stat(cur_file, &st) == 0 && S_ISDIR(st.st_mode)) {
456 if (!(option_mask32 & OPT_h))
458 matched += grep_dir(cur_file);
462 /* else: fopen(dir) will succeed, but reading won't */
463 file = fopen(cur_file, "r");
465 if (!SUPPRESS_ERR_MSGS)
466 bb_perror_msg("%s", cur_file);
471 matched += grep_file(file);
472 fclose_if_not_stdin(file);
475 /* we found a match but were told to be quiet, stop here and
481 /* destroy all the elments in the pattern list */
482 if (ENABLE_FEATURE_CLEAN_UP) {
483 while (pattern_head) {
484 llist_t *pattern_head_ptr = pattern_head;
485 grep_list_data_t *gl =
486 (grep_list_data_t *)pattern_head_ptr->data;
488 pattern_head = pattern_head->link;
489 if ((gl->flg_mem_alocated_compiled & PATTERN_MEM_A))
491 if ((gl->flg_mem_alocated_compiled & COMPILED))
492 regfree(&(gl->preg));
493 free(pattern_head_ptr);
496 /* 0 = success, 1 = failed, 2 = error */
497 /* If the -q option is specified, the exit status shall be zero
498 * if an input line is selected, even if an error was detected. */
499 if (BE_QUIET && matched)
503 return !matched; /* invert return value 0 = success, 1 = failed */