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, 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.
24 static unsigned long opt;
25 #define GREP_OPTS "lnqvscFiHhe:f:L"
26 #define GREP_OPT_l (1<<0)
27 #define PRINT_FILES_WITH_MATCHES (opt & GREP_OPT_l)
28 #define GREP_OPT_n (1<<1)
29 #define PRINT_LINE_NUM (opt & GREP_OPT_n)
30 #define GREP_OPT_q (1<<2)
31 #define BE_QUIET (opt & GREP_OPT_q)
32 #define GREP_OPT_v (1<<3)
33 typedef char invert_search_t;
34 static invert_search_t invert_search;
35 #define GREP_OPT_s (1<<4)
36 #define SUPPRESS_ERR_MSGS (opt & GREP_OPT_s)
37 #define GREP_OPT_c (1<<5)
38 #define PRINT_MATCH_COUNTS (opt & GREP_OPT_c)
39 #define GREP_OPT_F (1<<6)
40 #define FGREP_FLAG (opt & GREP_OPT_F)
41 #define GREP_OPT_i (1<<7)
42 #define GREP_OPT_H (1<<8)
43 #define GREP_OPT_h (1<<9)
44 #define GREP_OPT_e (1<<10)
45 #define GREP_OPT_f (1<<11)
46 #define GREP_OPT_L (1<<12)
47 #define PRINT_FILES_WITHOUT_MATCHES ((opt & GREP_OPT_L) != 0)
48 #if ENABLE_FEATURE_GREP_CONTEXT
49 #define GREP_OPT_CONTEXT "A:B:C"
50 #define GREP_OPT_A (1<<13)
51 #define GREP_OPT_B (1<<14)
52 #define GREP_OPT_C (1<<15)
53 #define GREP_OPT_E (1<<16)
55 #define GREP_OPT_CONTEXT ""
56 #define GREP_OPT_A (0)
57 #define GREP_OPT_B (0)
58 #define GREP_OPT_C (0)
59 #define GREP_OPT_E (1<<13)
61 #if ENABLE_FEATURE_GREP_EGREP_ALIAS
62 # define OPT_EGREP "E"
68 static int print_filename;
70 #if ENABLE_FEATURE_GREP_CONTEXT
71 static int lines_before;
72 static int lines_after;
73 static char **before_buf;
74 static int last_line_printed;
75 #endif /* ENABLE_FEATURE_GREP_CONTEXT */
77 /* globals used internally */
78 static llist_t *pattern_head; /* growable list of patterns to match */
79 static char *cur_file; /* the current file we are reading */
81 typedef struct GREP_LIST_DATA {
84 #define PATTERN_MEM_A 1
86 int flg_mem_alocated_compiled;
89 static void print_line(const char *line, int linenum, char decoration)
91 #if ENABLE_FEATURE_GREP_CONTEXT
92 /* possibly print the little '--' separator */
93 if ((lines_before || lines_after) && last_line_printed &&
94 last_line_printed < linenum - 1) {
97 last_line_printed = linenum;
99 if (print_filename > 0)
100 printf("%s%c", cur_file, decoration);
102 printf("%i%c", linenum, decoration);
107 static int grep_file(FILE *file)
113 #if ENABLE_FEATURE_GREP_CONTEXT
114 int print_n_lines_after = 0;
115 int curpos = 0; /* track where we are in the circular 'before' buffer */
116 int idx = 0; /* used for iteration through the circular buffer */
117 #endif /* ENABLE_FEATURE_GREP_CONTEXT */
119 while ((line = bb_get_chomped_line_from_file(file)) != NULL) {
120 llist_t *pattern_ptr = pattern_head;
121 grep_list_data_t * gl;
125 while (pattern_ptr) {
126 gl = (grep_list_data_t *)pattern_ptr->data;
128 ret = strstr(line, gl->pattern) != NULL;
131 * test for a postitive-assertion match (regexec returns success (0)
132 * and the user did not specify invert search), or a negative-assertion
133 * match (regexec returns failure (REG_NOMATCH) and the user specified
136 if(!(gl->flg_mem_alocated_compiled & COMPILED)) {
137 gl->flg_mem_alocated_compiled |= COMPILED;
138 xregcomp(&(gl->preg), gl->pattern, reflags);
140 ret |= regexec(&(gl->preg), line, 0, NULL, 0) == 0;
142 pattern_ptr = pattern_ptr->link;
143 } /* while (pattern_ptr) */
145 if ((ret ^ invert_search)) {
147 if (PRINT_FILES_WITH_MATCHES || BE_QUIET)
150 /* if we found a match but were told to be quiet, stop here */
151 if (BE_QUIET || PRINT_FILES_WITHOUT_MATCHES)
154 /* keep track of matches */
157 /* if we're just printing filenames, we stop after the first match */
158 if (PRINT_FILES_WITH_MATCHES)
161 /* print the matched line */
162 if (PRINT_MATCH_COUNTS == 0) {
163 #if ENABLE_FEATURE_GREP_CONTEXT
164 int prevpos = (curpos == 0) ? lines_before - 1 : curpos - 1;
166 /* if we were told to print 'before' lines and there is at least
167 * one line in the circular buffer, print them */
168 if (lines_before && before_buf[prevpos] != NULL) {
169 int first_buf_entry_line_num = linenum - lines_before;
171 /* advance to the first entry in the circular buffer, and
172 * figure out the line number is of the first line in the
175 while (before_buf[idx] == NULL) {
176 idx = (idx + 1) % lines_before;
177 first_buf_entry_line_num++;
180 /* now print each line in the buffer, clearing them as we go */
181 while (before_buf[idx] != NULL) {
182 print_line(before_buf[idx], first_buf_entry_line_num, '-');
183 free(before_buf[idx]);
184 before_buf[idx] = NULL;
185 idx = (idx + 1) % lines_before;
186 first_buf_entry_line_num++;
190 /* make a note that we need to print 'after' lines */
191 print_n_lines_after = lines_after;
193 print_line(line, linenum, ':');
196 #if ENABLE_FEATURE_GREP_CONTEXT
197 else { /* no match */
198 /* Add the line to the circular 'before' buffer */
200 free(before_buf[curpos]);
201 before_buf[curpos] = xstrdup(line);
202 curpos = (curpos + 1) % lines_before;
206 /* if we need to print some context lines after the last match, do so */
207 if (print_n_lines_after && (last_line_printed != linenum)) {
208 print_line(line, linenum, '-');
209 print_n_lines_after--;
211 #endif /* ENABLE_FEATURE_GREP_CONTEXT */
216 /* special-case file post-processing for options where we don't print line
217 * matches, just filenames and possibly match counts */
219 /* grep -c: print [filename:]count, even if count is zero */
220 if (PRINT_MATCH_COUNTS) {
221 if (print_filename > 0)
222 printf("%s:", cur_file);
223 printf("%d\n", nmatches);
226 /* grep -l: print just the filename, but only if we grepped the line in the file */
227 if (PRINT_FILES_WITH_MATCHES && nmatches > 0) {
231 /* grep -L: print just the filename, but only if we didn't grep the line in the file */
232 if (PRINT_FILES_WITHOUT_MATCHES && nmatches == 0) {
239 #if ENABLE_FEATURE_CLEAN_UP
240 #define new_grep_list_data(p, m) add_grep_list_data(p, m)
241 static char * add_grep_list_data(char *pattern, int flg_used_mem)
243 #define new_grep_list_data(p, m) add_grep_list_data(p)
244 static char * add_grep_list_data(char *pattern)
247 grep_list_data_t *gl = xmalloc(sizeof(grep_list_data_t));
248 gl->pattern = pattern;
249 #if ENABLE_FEATURE_CLEAN_UP
250 gl->flg_mem_alocated_compiled = flg_used_mem;
252 gl->flg_mem_alocated_compiled = 0;
258 static void load_regexes_from_file(llist_t *fopt)
265 char *ffile = cur->data;
269 f = xfopen(ffile, "r");
270 while ((line = bb_get_chomped_line_from_file(f)) != NULL) {
271 llist_add_to(&pattern_head,
272 new_grep_list_data(line, PATTERN_MEM_A));
278 int grep_main(int argc, char **argv)
282 llist_t *fopt = NULL;
283 int error_open_count = 0;
285 /* do normal option parsing */
286 #if ENABLE_FEATURE_GREP_CONTEXT
293 bb_opt_complementally = "H-h:e::f::C-AB";
294 opt = bb_getopt_ulflags(argc, argv,
295 GREP_OPTS GREP_OPT_CONTEXT OPT_EGREP,
296 &pattern_head, &fopt,
297 &slines_after, &slines_before, &Copt);
299 if(opt & GREP_OPT_C) {
300 /* C option unseted A and B options, but next -A or -B
301 may be ovewrite own option */
302 if(!(opt & GREP_OPT_A)) /* not overwtited */
304 if(!(opt & GREP_OPT_B)) /* not overwtited */
305 slines_before = Copt;
306 opt |= GREP_OPT_A|GREP_OPT_B; /* set for parse now */
308 if(opt & GREP_OPT_A) {
309 lines_after = strtoul(slines_after, &junk, 10);
311 bb_error_msg_and_die(bb_msg_invalid_arg, slines_after, "-A");
313 if(opt & GREP_OPT_B) {
314 lines_before = strtoul(slines_before, &junk, 10);
316 bb_error_msg_and_die(bb_msg_invalid_arg, slines_before, "-B");
318 /* sanity checks after parse may be invalid numbers ;-) */
319 if ((opt & (GREP_OPT_c|GREP_OPT_q|GREP_OPT_l|GREP_OPT_L))) {
323 } else if(lines_before > 0)
324 before_buf = (char **)xzalloc(lines_before * sizeof(char *));
327 /* with auto sanity checks */
328 bb_opt_complementally = "H-h:e::f::c-n:q-n:l-n";
329 opt = bb_getopt_ulflags(argc, argv, GREP_OPTS OPT_EGREP,
330 &pattern_head, &fopt);
332 invert_search = (opt & GREP_OPT_v) != 0; /* 0 | 1 */
338 if (pattern_head != NULL) {
339 /* convert char *argv[] to grep_list_data_t */
342 for(cur = pattern_head; cur; cur = cur->link)
343 cur->data = new_grep_list_data(cur->data, 0);
346 load_regexes_from_file(fopt);
348 if(ENABLE_FEATURE_GREP_FGREP_ALIAS && bb_applet_name[0] == 'f')
351 if(ENABLE_FEATURE_GREP_EGREP_ALIAS &&
352 (bb_applet_name[0] == 'e' || (opt & GREP_OPT_E)))
353 reflags = REG_EXTENDED | REG_NOSUB;
358 reflags |= REG_ICASE;
363 /* if we didn't get a pattern from a -e and no command file was specified,
364 * argv[optind] should be the pattern. no pattern, no worky */
365 if (pattern_head == NULL) {
369 char *pattern = new_grep_list_data(*argv++, 0);
371 llist_add_to(&pattern_head, pattern);
376 /* argv[(optind)..(argc-1)] should be names of file to grep through. If
377 * there is more than one file to grep, we will print the filenames */
381 /* If no files were specified, or '-' was specified, take input from
382 * stdin. Otherwise, we grep through all the files specified. */
383 } else if (argc == 0) {
389 if(!cur_file || (*cur_file == '-' && !cur_file[1])) {
390 cur_file = "(standard input)";
393 file = fopen(cur_file, "r");
396 if (!SUPPRESS_ERR_MSGS)
397 bb_perror_msg("%s", cur_file);
400 matched += grep_file(file);
402 /* we found a match but were told to be quiet, stop here and
410 /* destroy all the elments in the pattern list */
411 if (ENABLE_FEATURE_CLEAN_UP) {
412 while (pattern_head) {
413 llist_t *pattern_head_ptr = pattern_head;
414 grep_list_data_t *gl =
415 (grep_list_data_t *)pattern_head_ptr->data;
417 pattern_head = pattern_head->link;
418 if((gl->flg_mem_alocated_compiled & PATTERN_MEM_A))
420 if((gl->flg_mem_alocated_compiled & COMPILED))
421 regfree(&(gl->preg));
422 free(pattern_head_ptr);
425 /* 0 = success, 1 = failed, 2 = error */
426 /* If the -q option is specified, the exit status shall be zero
427 * if an input line is selected, even if an error was detected. */
428 if(BE_QUIET && matched)
432 return !matched; /* invert return value 0 = success, 1 = failed */