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