grep: yet another fixlet for EXTRA_COMPAT
[oweals/busybox.git] / findutils / grep.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Mini grep implementation for busybox using libc regex.
4  *
5  * Copyright (C) 1999,2000,2001 by Lineo, inc. and Mark Whitley
6  * Copyright (C) 1999,2000,2001 by Mark Whitley <markw@codepoet.org>
7  *
8  * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
9  */
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 */
13 /*
14  * 2004,2006 (C) Vladimir Oleynik <dzo@simtreas.ru> -
15  * correction "-e pattern1 -e pattern2" logic and more optimizations.
16  * precompiled regex
17  */
18 /*
19  * (C) 2006 Jac Goudsmit added -o option
20  */
21
22 #include "libbb.h"
23 #include "xregex.h"
24
25 /* options */
26 #define OPTSTR_GREP \
27         "lnqvscFiHhe:f:Lorm:" \
28         USE_FEATURE_GREP_CONTEXT("A:B:C:") \
29         USE_FEATURE_GREP_EGREP_ALIAS("E") \
30         USE_DESKTOP("w") \
31         "aI"
32 /* ignored: -a "assume all files to be text" */
33 /* ignored: -I "assume binary files have no matches" */
34
35 enum {
36         OPTBIT_l, /* list matched file names only */
37         OPTBIT_n, /* print line# */
38         OPTBIT_q, /* quiet - exit(EXIT_SUCCESS) of first match */
39         OPTBIT_v, /* invert the match, to select non-matching lines */
40         OPTBIT_s, /* suppress errors about file open errors */
41         OPTBIT_c, /* count matches per file (suppresses normal output) */
42         OPTBIT_F, /* literal match */
43         OPTBIT_i, /* case-insensitive */
44         OPTBIT_H, /* force filename display */
45         OPTBIT_h, /* inhibit filename display */
46         OPTBIT_e, /* -e PATTERN */
47         OPTBIT_f, /* -f FILE_WITH_PATTERNS */
48         OPTBIT_L, /* list unmatched file names only */
49         OPTBIT_o, /* show only matching parts of lines */
50         OPTBIT_r, /* recurse dirs */
51         OPTBIT_m, /* -m MAX_MATCHES */
52         USE_FEATURE_GREP_CONTEXT(    OPTBIT_A ,) /* -A NUM: after-match context */
53         USE_FEATURE_GREP_CONTEXT(    OPTBIT_B ,) /* -B NUM: before-match context */
54         USE_FEATURE_GREP_CONTEXT(    OPTBIT_C ,) /* -C NUM: -A and -B combined */
55         USE_FEATURE_GREP_EGREP_ALIAS(OPTBIT_E ,) /* extended regexp */
56         USE_DESKTOP(                 OPTBIT_w ,) /* whole word match */
57         OPT_l = 1 << OPTBIT_l,
58         OPT_n = 1 << OPTBIT_n,
59         OPT_q = 1 << OPTBIT_q,
60         OPT_v = 1 << OPTBIT_v,
61         OPT_s = 1 << OPTBIT_s,
62         OPT_c = 1 << OPTBIT_c,
63         OPT_F = 1 << OPTBIT_F,
64         OPT_i = 1 << OPTBIT_i,
65         OPT_H = 1 << OPTBIT_H,
66         OPT_h = 1 << OPTBIT_h,
67         OPT_e = 1 << OPTBIT_e,
68         OPT_f = 1 << OPTBIT_f,
69         OPT_L = 1 << OPTBIT_L,
70         OPT_o = 1 << OPTBIT_o,
71         OPT_r = 1 << OPTBIT_r,
72         OPT_m = 1 << OPTBIT_m,
73         OPT_A = USE_FEATURE_GREP_CONTEXT(    (1 << OPTBIT_A)) + 0,
74         OPT_B = USE_FEATURE_GREP_CONTEXT(    (1 << OPTBIT_B)) + 0,
75         OPT_C = USE_FEATURE_GREP_CONTEXT(    (1 << OPTBIT_C)) + 0,
76         OPT_E = USE_FEATURE_GREP_EGREP_ALIAS((1 << OPTBIT_E)) + 0,
77         OPT_w = USE_DESKTOP(                 (1 << OPTBIT_w)) + 0,
78 };
79
80 #define PRINT_FILES_WITH_MATCHES    (option_mask32 & OPT_l)
81 #define PRINT_LINE_NUM              (option_mask32 & OPT_n)
82 #define BE_QUIET                    (option_mask32 & OPT_q)
83 #define SUPPRESS_ERR_MSGS           (option_mask32 & OPT_s)
84 #define PRINT_MATCH_COUNTS          (option_mask32 & OPT_c)
85 #define FGREP_FLAG                  (option_mask32 & OPT_F)
86 #define PRINT_FILES_WITHOUT_MATCHES (option_mask32 & OPT_L)
87
88 struct globals {
89         int max_matches;
90 #if !ENABLE_EXTRA_COMPAT
91         int reflags;
92 #else
93         RE_TRANSLATE_TYPE case_fold; /* RE_TRANSLATE_TYPE is [[un]signed] char* */
94 #endif
95         smalluint invert_search;
96         smalluint print_filename;
97         smalluint open_errors;
98 #if ENABLE_FEATURE_GREP_CONTEXT
99         smalluint did_print_line;
100         int lines_before;
101         int lines_after;
102         char **before_buf;
103         USE_EXTRA_COMPAT(size_t *before_buf_size;)
104         int last_line_printed;
105 #endif
106         /* globals used internally */
107         llist_t *pattern_head;   /* growable list of patterns to match */
108         const char *cur_file;    /* the current file we are reading */
109 };
110 #define G (*(struct globals*)&bb_common_bufsiz1)
111 #define INIT_G() do { \
112         struct G_sizecheck { \
113                 char G_sizecheck[sizeof(G) > COMMON_BUFSIZE ? -1 : 1]; \
114         }; \
115 } while (0)
116 #define max_matches       (G.max_matches         )
117 #if !ENABLE_EXTRA_COMPAT
118 #define reflags           (G.reflags             )
119 #else
120 #define case_fold         (G.case_fold           )
121 /* http://www.delorie.com/gnu/docs/regex/regex_46.html */
122 #define reflags           re_syntax_options
123 #undef REG_NOSUB
124 #undef REG_EXTENDED
125 #undef REG_ICASE
126 #define REG_NOSUB    bug:is:here /* should not be used */
127 #define REG_EXTENDED RE_SYNTAX_EGREP
128 #define REG_ICASE    bug:is:here /* should not be used */
129 #endif
130 #define invert_search     (G.invert_search       )
131 #define print_filename    (G.print_filename      )
132 #define open_errors       (G.open_errors         )
133 #define did_print_line    (G.did_print_line      )
134 #define lines_before      (G.lines_before        )
135 #define lines_after       (G.lines_after         )
136 #define before_buf        (G.before_buf          )
137 #define before_buf_size   (G.before_buf_size     )
138 #define last_line_printed (G.last_line_printed   )
139 #define pattern_head      (G.pattern_head        )
140 #define cur_file          (G.cur_file            )
141
142
143 typedef struct grep_list_data_t {
144         char *pattern;
145 /* for GNU regex, matched_range must be persistent across grep_file() calls */
146 #if !ENABLE_EXTRA_COMPAT
147         regex_t compiled_regex;
148         regmatch_t matched_range;
149 #else
150         struct re_pattern_buffer compiled_regex;
151         struct re_registers matched_range;
152 #endif
153 #define ALLOCATED 1
154 #define COMPILED 2
155         int flg_mem_alocated_compiled;
156 } grep_list_data_t;
157
158 #if !ENABLE_EXTRA_COMPAT
159 #define print_line(line, line_len, linenum, decoration) \
160         print_line(line, linenum, decoration)
161 #endif
162 static void print_line(const char *line, size_t line_len, int linenum, char decoration)
163 {
164 #if ENABLE_FEATURE_GREP_CONTEXT
165         /* Happens when we go to next file, immediately hit match
166          * and try to print prev context... from prev file! Don't do it */
167         if (linenum < 1)
168                 return;
169         /* possibly print the little '--' separator */
170         if ((lines_before || lines_after) && did_print_line
171          && last_line_printed != linenum - 1
172         ) {
173                 puts("--");
174         }
175         /* guard against printing "--" before first line of first file */
176         did_print_line = 1;
177         last_line_printed = linenum;
178 #endif
179         if (print_filename)
180                 printf("%s%c", cur_file, decoration);
181         if (PRINT_LINE_NUM)
182                 printf("%i%c", linenum, decoration);
183         /* Emulate weird GNU grep behavior with -ov */
184         if ((option_mask32 & (OPT_v|OPT_o)) != (OPT_v|OPT_o)) {
185 #if !ENABLE_EXTRA_COMPAT
186                 puts(line);
187 #else
188                 fwrite(line, 1, line_len, stdout);
189                 putchar('\n');
190 #endif
191         }
192 }
193
194 #if ENABLE_EXTRA_COMPAT
195 /* Unlike getline, this one removes trailing '\n' */
196 static ssize_t FAST_FUNC bb_getline(char **line_ptr, size_t *line_alloc_len, FILE *file)
197 {
198         ssize_t res_sz;
199         char *line;
200
201         res_sz = getline(line_ptr, line_alloc_len, file);
202         line = *line_ptr;
203
204         if (res_sz > 0) {
205                 if (line[res_sz - 1] == '\n')
206                         line[--res_sz] = '\0';
207         } else {
208                 free(line); /* uclibc allocates a buffer even on EOF. WTF? */
209         }
210         return res_sz;
211 }
212 #endif
213
214 static int grep_file(FILE *file)
215 {
216         smalluint found;
217         int linenum = 0;
218         int nmatches = 0;
219 #if !ENABLE_EXTRA_COMPAT
220         char *line;
221 #else
222         char *line = NULL;
223         ssize_t line_len;
224         size_t line_alloc_len;
225 #define rm_so start[0]
226 #define rm_eo end[0]
227 #endif
228 #if ENABLE_FEATURE_GREP_CONTEXT
229         int print_n_lines_after = 0;
230         int curpos = 0; /* track where we are in the circular 'before' buffer */
231         int idx = 0; /* used for iteration through the circular buffer */
232 #else
233         enum { print_n_lines_after = 0 };
234 #endif /* ENABLE_FEATURE_GREP_CONTEXT */
235
236         while (
237 #if !ENABLE_EXTRA_COMPAT
238                 (line = xmalloc_fgetline(file)) != NULL
239 #else
240                 (line_len = bb_getline(&line, &line_alloc_len, file)) >= 0
241 #endif
242         ) {
243                 llist_t *pattern_ptr = pattern_head;
244                 grep_list_data_t *gl = gl; /* for gcc */
245
246                 linenum++;
247                 found = 0;
248                 while (pattern_ptr) {
249                         gl = (grep_list_data_t *)pattern_ptr->data;
250                         if (FGREP_FLAG) {
251                                 found |= (strstr(line, gl->pattern) != NULL);
252                         } else {
253                                 if (!(gl->flg_mem_alocated_compiled & COMPILED)) {
254                                         gl->flg_mem_alocated_compiled |= COMPILED;
255 #if !ENABLE_EXTRA_COMPAT
256                                         xregcomp(&gl->compiled_regex, gl->pattern, reflags);
257 #else
258                                         memset(&gl->compiled_regex, 0, sizeof(gl->compiled_regex));
259                                         gl->compiled_regex.translate = case_fold; /* for -i */
260                                         if (re_compile_pattern(gl->pattern, strlen(gl->pattern), &gl->compiled_regex))
261                                                 bb_error_msg_and_die("bad regex '%s'", gl->pattern);
262 #endif
263                                 }
264 #if !ENABLE_EXTRA_COMPAT
265                                 gl->matched_range.rm_so = 0;
266                                 gl->matched_range.rm_eo = 0;
267 #endif
268                                 if (
269 #if !ENABLE_EXTRA_COMPAT
270                                         regexec(&gl->compiled_regex, line, 1, &gl->matched_range, 0) == 0
271 #else
272                                         re_search(&gl->compiled_regex, line, line_len,
273                                                         /*start:*/ 0, /*range:*/ line_len,
274                                                         &gl->matched_range) >= 0
275 #endif
276                                 ) {
277                                         if (!(option_mask32 & OPT_w))
278                                                 found = 1;
279                                         else {
280                                                 char c = ' ';
281                                                 if (gl->matched_range.rm_so)
282                                                         c = line[gl->matched_range.rm_so - 1];
283                                                 if (!isalnum(c) && c != '_') {
284                                                         c = line[gl->matched_range.rm_eo];
285                                                         if (!c || (!isalnum(c) && c != '_'))
286                                                                 found = 1;
287                                                 }
288                                         }
289                                 }
290                         }
291                         /* If it's non-inverted search, we can stop
292                          * at first match */
293                         if (found && !invert_search)
294                                 goto do_found;
295                         pattern_ptr = pattern_ptr->link;
296                 } /* while (pattern_ptr) */
297
298                 if (found ^ invert_search) {
299  do_found:
300                         /* keep track of matches */
301                         nmatches++;
302
303                         /* quiet/print (non)matching file names only? */
304                         if (option_mask32 & (OPT_q|OPT_l|OPT_L)) {
305                                 free(line); /* we don't need line anymore */
306                                 if (BE_QUIET) {
307                                         /* manpage says about -q:
308                                          * "exit immediately with zero status
309                                          * if any match is found,
310                                          * even if errors were detected" */
311                                         exit(EXIT_SUCCESS);
312                                 }
313                                 /* if we're just printing filenames, we stop after the first match */
314                                 if (PRINT_FILES_WITH_MATCHES) {
315                                         puts(cur_file);
316                                         /* fall through to "return 1" */
317                                 }
318                                 /* OPT_L aka PRINT_FILES_WITHOUT_MATCHES: return early */
319                                 return 1; /* one match */
320                         }
321
322 #if ENABLE_FEATURE_GREP_CONTEXT
323                         /* Were we printing context and saw next (unwanted) match? */
324                         if ((option_mask32 & OPT_m) && nmatches > max_matches)
325                                 break;
326 #endif
327
328                         /* print the matched line */
329                         if (PRINT_MATCH_COUNTS == 0) {
330 #if ENABLE_FEATURE_GREP_CONTEXT
331                                 int prevpos = (curpos == 0) ? lines_before - 1 : curpos - 1;
332
333                                 /* if we were told to print 'before' lines and there is at least
334                                  * one line in the circular buffer, print them */
335                                 if (lines_before && before_buf[prevpos] != NULL) {
336                                         int first_buf_entry_line_num = linenum - lines_before;
337
338                                         /* advance to the first entry in the circular buffer, and
339                                          * figure out the line number is of the first line in the
340                                          * buffer */
341                                         idx = curpos;
342                                         while (before_buf[idx] == NULL) {
343                                                 idx = (idx + 1) % lines_before;
344                                                 first_buf_entry_line_num++;
345                                         }
346
347                                         /* now print each line in the buffer, clearing them as we go */
348                                         while (before_buf[idx] != NULL) {
349                                                 print_line(before_buf[idx], before_buf_size[idx], first_buf_entry_line_num, '-');
350                                                 free(before_buf[idx]);
351                                                 before_buf[idx] = NULL;
352                                                 idx = (idx + 1) % lines_before;
353                                                 first_buf_entry_line_num++;
354                                         }
355                                 }
356
357                                 /* make a note that we need to print 'after' lines */
358                                 print_n_lines_after = lines_after;
359 #endif
360                                 if (option_mask32 & OPT_o) {
361                                         if (FGREP_FLAG) {
362                                                 /* -Fo just prints the pattern
363                                                  * (unless -v: -Fov doesnt print anything at all) */
364                                                 if (found)
365                                                         print_line(gl->pattern, strlen(gl->pattern), linenum, ':');
366                                         } else {
367                                                 line[gl->matched_range.rm_eo] = '\0';
368                                                 print_line(line + gl->matched_range.rm_so,
369                                                                 gl->matched_range.rm_eo - gl->matched_range.rm_so,
370                                                                 linenum, ':');
371                                         }
372                                 } else {
373                                         print_line(line, line_len, linenum, ':');
374                                 }
375                         }
376                 }
377 #if ENABLE_FEATURE_GREP_CONTEXT
378                 else { /* no match */
379                         /* if we need to print some context lines after the last match, do so */
380                         if (print_n_lines_after) {
381                                 print_line(line, strlen(line), linenum, '-');
382                                 print_n_lines_after--;
383                         } else if (lines_before) {
384                                 /* Add the line to the circular 'before' buffer */
385                                 free(before_buf[curpos]);
386                                 before_buf[curpos] = line;
387                                 USE_EXTRA_COMPAT(before_buf_size[curpos] = line_len;)
388                                 curpos = (curpos + 1) % lines_before;
389                                 /* avoid free(line) - we took the line */
390                                 line = NULL;
391                         }
392                 }
393
394 #endif /* ENABLE_FEATURE_GREP_CONTEXT */
395 #if !ENABLE_EXTRA_COMPAT
396                 free(line);
397 #endif
398                 /* Did we print all context after last requested match? */
399                 if ((option_mask32 & OPT_m)
400                  && !print_n_lines_after && nmatches == max_matches)
401                         break;
402         } /* while (read line) */
403
404         /* special-case file post-processing for options where we don't print line
405          * matches, just filenames and possibly match counts */
406
407         /* grep -c: print [filename:]count, even if count is zero */
408         if (PRINT_MATCH_COUNTS) {
409                 if (print_filename)
410                         printf("%s:", cur_file);
411                 printf("%d\n", nmatches);
412         }
413
414         /* grep -L: print just the filename */
415         if (PRINT_FILES_WITHOUT_MATCHES) {
416                 /* nmatches is zero, no need to check it:
417                  * we return 1 early if we detected a match
418                  * and PRINT_FILES_WITHOUT_MATCHES is set */
419                 puts(cur_file);
420         }
421
422         return nmatches;
423 }
424
425 #if ENABLE_FEATURE_CLEAN_UP
426 #define new_grep_list_data(p, m) add_grep_list_data(p, m)
427 static char *add_grep_list_data(char *pattern, int flg_used_mem)
428 #else
429 #define new_grep_list_data(p, m) add_grep_list_data(p)
430 static char *add_grep_list_data(char *pattern)
431 #endif
432 {
433         grep_list_data_t *gl = xzalloc(sizeof(*gl));
434         gl->pattern = pattern;
435 #if ENABLE_FEATURE_CLEAN_UP
436         gl->flg_mem_alocated_compiled = flg_used_mem;
437 #else
438         /*gl->flg_mem_alocated_compiled = 0;*/
439 #endif
440         return (char *)gl;
441 }
442
443 static void load_regexes_from_file(llist_t *fopt)
444 {
445         char *line;
446         FILE *f;
447
448         while (fopt) {
449                 llist_t *cur = fopt;
450                 char *ffile = cur->data;
451
452                 fopt = cur->link;
453                 free(cur);
454                 f = xfopen_stdin(ffile);
455                 while ((line = xmalloc_fgetline(f)) != NULL) {
456                         llist_add_to(&pattern_head,
457                                 new_grep_list_data(line, ALLOCATED));
458                 }
459         }
460 }
461
462 static int FAST_FUNC file_action_grep(const char *filename,
463                         struct stat *statbuf UNUSED_PARAM,
464                         void* matched,
465                         int depth UNUSED_PARAM)
466 {
467         FILE *file = fopen_for_read(filename);
468         if (file == NULL) {
469                 if (!SUPPRESS_ERR_MSGS)
470                         bb_simple_perror_msg(filename);
471                 open_errors = 1;
472                 return 0;
473         }
474         cur_file = filename;
475         *(int*)matched += grep_file(file);
476         fclose(file);
477         return 1;
478 }
479
480 static int grep_dir(const char *dir)
481 {
482         int matched = 0;
483         recursive_action(dir,
484                 /* recurse=yes */ ACTION_RECURSE |
485                 /* followLinks=no */
486                 /* depthFirst=yes */ ACTION_DEPTHFIRST,
487                 /* fileAction= */ file_action_grep,
488                 /* dirAction= */ NULL,
489                 /* userData= */ &matched,
490                 /* depth= */ 0);
491         return matched;
492 }
493
494 int grep_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
495 int grep_main(int argc, char **argv)
496 {
497         FILE *file;
498         int matched;
499         llist_t *fopt = NULL;
500
501         /* do normal option parsing */
502 #if ENABLE_FEATURE_GREP_CONTEXT
503         int Copt;
504
505         /* -H unsets -h; -C unsets -A,-B; -e,-f are lists;
506          * -m,-A,-B,-C have numeric param */
507         opt_complementary = "H-h:C-AB:e::f::m+:A+:B+:C+";
508         getopt32(argv,
509                 OPTSTR_GREP,
510                 &pattern_head, &fopt, &max_matches,
511                 &lines_after, &lines_before, &Copt);
512
513         if (option_mask32 & OPT_C) {
514                 /* -C unsets prev -A and -B, but following -A or -B
515                    may override it */
516                 if (!(option_mask32 & OPT_A)) /* not overridden */
517                         lines_after = Copt;
518                 if (!(option_mask32 & OPT_B)) /* not overridden */
519                         lines_before = Copt;
520         }
521         /* sanity checks */
522         if (option_mask32 & (OPT_c|OPT_q|OPT_l|OPT_L)) {
523                 option_mask32 &= ~OPT_n;
524                 lines_before = 0;
525                 lines_after = 0;
526         } else if (lines_before > 0) {
527                 before_buf = xzalloc(lines_before * sizeof(before_buf[0]));
528                 USE_EXTRA_COMPAT(before_buf_size = xzalloc(lines_before * sizeof(before_buf_size[0]));)
529         }
530 #else
531         /* with auto sanity checks */
532         /* -H unsets -h; -c,-q or -l unset -n; -e,-f are lists; -m N */
533         opt_complementary = "H-h:c-n:q-n:l-n:e::f::m+";
534         getopt32(argv, OPTSTR_GREP,
535                 &pattern_head, &fopt, &max_matches);
536 #endif
537         invert_search = ((option_mask32 & OPT_v) != 0); /* 0 | 1 */
538
539         if (pattern_head != NULL) {
540                 /* convert char **argv to grep_list_data_t */
541                 llist_t *cur;
542
543                 for (cur = pattern_head; cur; cur = cur->link)
544                         cur->data = new_grep_list_data(cur->data, 0);
545         }
546         if (option_mask32 & OPT_f)
547                 load_regexes_from_file(fopt);
548
549         if (ENABLE_FEATURE_GREP_FGREP_ALIAS && applet_name[0] == 'f')
550                 option_mask32 |= OPT_F;
551
552 #if !ENABLE_EXTRA_COMPAT
553         if (!(option_mask32 & (OPT_o | OPT_w)))
554                 reflags = REG_NOSUB;
555 #endif
556
557         if (ENABLE_FEATURE_GREP_EGREP_ALIAS
558          && (applet_name[0] == 'e' || (option_mask32 & OPT_E))
559         ) {
560                 reflags |= REG_EXTENDED;
561         }
562 #if ENABLE_EXTRA_COMPAT
563         else {
564                 reflags = RE_SYNTAX_GREP;
565         }
566 #endif
567
568         if (option_mask32 & OPT_i) {
569 #if !ENABLE_EXTRA_COMPAT
570                 reflags |= REG_ICASE;
571 #else
572                 int i;
573                 case_fold = xmalloc(256);
574                 for (i = 0; i < 256; i++)
575                         case_fold[i] = (unsigned char)i;
576                 for (i = 'a'; i <= 'z'; i++)
577                         case_fold[i] = (unsigned char)(i - ('a' - 'A'));
578 #endif
579         }
580
581         argv += optind;
582         argc -= optind;
583
584         /* if we didn't get a pattern from -e and no command file was specified,
585          * first parameter should be the pattern. no pattern, no worky */
586         if (pattern_head == NULL) {
587                 char *pattern;
588                 if (*argv == NULL)
589                         bb_show_usage();
590                 pattern = new_grep_list_data(*argv++, 0);
591                 llist_add_to(&pattern_head, pattern);
592                 argc--;
593         }
594
595         /* argv[0..(argc-1)] should be names of file to grep through. If
596          * there is more than one file to grep, we will print the filenames. */
597         if (argc > 1)
598                 print_filename = 1;
599         /* -H / -h of course override */
600         if (option_mask32 & OPT_H)
601                 print_filename = 1;
602         if (option_mask32 & OPT_h)
603                 print_filename = 0;
604
605         /* If no files were specified, or '-' was specified, take input from
606          * stdin. Otherwise, we grep through all the files specified. */
607         matched = 0;
608         do {
609                 cur_file = *argv++;
610                 file = stdin;
611                 if (!cur_file || LONE_DASH(cur_file)) {
612                         cur_file = "(standard input)";
613                 } else {
614                         if (option_mask32 & OPT_r) {
615                                 struct stat st;
616                                 if (stat(cur_file, &st) == 0 && S_ISDIR(st.st_mode)) {
617                                         if (!(option_mask32 & OPT_h))
618                                                 print_filename = 1;
619                                         matched += grep_dir(cur_file);
620                                         goto grep_done;
621                                 }
622                         }
623                         /* else: fopen(dir) will succeed, but reading won't */
624                         file = fopen_for_read(cur_file);
625                         if (file == NULL) {
626                                 if (!SUPPRESS_ERR_MSGS)
627                                         bb_simple_perror_msg(cur_file);
628                                 open_errors = 1;
629                                 continue;
630                         }
631                 }
632                 matched += grep_file(file);
633                 fclose_if_not_stdin(file);
634  grep_done: ;
635         } while (--argc > 0);
636
637         /* destroy all the elments in the pattern list */
638         if (ENABLE_FEATURE_CLEAN_UP) {
639                 while (pattern_head) {
640                         llist_t *pattern_head_ptr = pattern_head;
641                         grep_list_data_t *gl = (grep_list_data_t *)pattern_head_ptr->data;
642
643                         pattern_head = pattern_head->link;
644                         if (gl->flg_mem_alocated_compiled & ALLOCATED)
645                                 free(gl->pattern);
646                         if (gl->flg_mem_alocated_compiled & COMPILED)
647                                 regfree(&gl->compiled_regex);
648                         free(gl);
649                         free(pattern_head_ptr);
650                 }
651         }
652         /* 0 = success, 1 = failed, 2 = error */
653         if (open_errors)
654                 return 2;
655         return !matched; /* invert return value: 0 = success, 1 = failed */
656 }