Fix segfault when cleaning up
[oweals/busybox.git] / findutils / grep.c
1 /*
2  * Mini grep implementation for busybox using libc regex.
3  *
4  * Copyright (C) 1999,2000,2001 by Lineo, inc. and Mark Whitley
5  * Copyright (C) 1999,2000,2001 by Mark Whitley <markw@codepoet.org> 
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15  * General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20  *
21  */
22
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <getopt.h>
26 #include <regex.h>
27 #include <string.h> /* for strerror() */
28 #include <errno.h>
29 #include "busybox.h"
30
31
32 extern int optind; /* in unistd.h */
33 extern void xregcomp(regex_t *preg, const char *regex, int cflags); /* in busybox.h */
34
35 /* options */
36 static int reflags            = REG_NOSUB; 
37 static int print_filename     = 0;
38 static int print_line_num     = 0;
39 static int print_match_counts = 0;
40 static int be_quiet           = 0;
41 static int invert_search      = 0;
42 static int suppress_err_msgs  = 0;
43 static int print_files_with_matches  = 0;
44 static int fgrep_flag            = 0;
45
46 #ifdef CONFIG_FEATURE_GREP_CONTEXT
47 extern char *optarg; /* in getopt.h */
48 static int lines_before      = 0;
49 static int lines_after       = 0;
50 static char **before_buf     = NULL;
51 static int last_line_printed = 0;
52 #endif /* CONFIG_FEATURE_GREP_CONTEXT */
53
54 /* globals used internally */
55 static llist_t *pattern_head = NULL; /* growable list of patterns to match */
56 static int matched; /* keeps track of whether we ever matched */
57 static char *cur_file = NULL; /* the current file we are reading */
58
59
60 static void print_line(const char *line, int linenum, char decoration)
61 {
62 #ifdef CONFIG_FEATURE_GREP_CONTEXT
63         /* possibly print the little '--' seperator */
64         if ((lines_before || lines_after) && last_line_printed &&
65                         last_line_printed < linenum - 1) {
66                 puts("--");
67         }
68         last_line_printed = linenum;
69 #endif
70         if (print_filename)
71                 printf("%s%c", cur_file, decoration);
72         if (print_line_num)
73                 printf("%i%c", linenum, decoration);
74         puts(line);
75 }
76
77
78 static void grep_file(FILE *file)
79 {
80         char *line = NULL;
81         int ret;
82         int linenum = 0;
83         int nmatches = 0;
84 #ifdef CONFIG_FEATURE_GREP_CONTEXT
85         int print_n_lines_after = 0;
86         int curpos = 0; /* track where we are in the circular 'before' buffer */
87         int idx = 0; /* used for iteration through the circular buffer */
88 #endif /* CONFIG_FEATURE_GREP_CONTEXT */ 
89
90         while ((line = bb_get_chomped_line_from_file(file)) != NULL) {
91                 llist_t *pattern_ptr = pattern_head;
92
93                 linenum++;
94
95                 while (pattern_ptr) {
96                         if (fgrep_flag) {
97                                 if (strstr(line, pattern_ptr->data)) {
98                                         /* Match found */
99                                         ret = 0;
100                                 } else {
101                                         ret = 1;
102                                 }
103                         } else {
104                                 /*
105                                  * test for a postitive-assertion match (regexec returns success (0)
106                                  * and the user did not specify invert search), or a negative-assertion
107                                  * match (regexec returns failure (REG_NOMATCH) and the user specified
108                                  * invert search)
109                                  */
110                                 regex_t regex;
111                                 xregcomp(&regex, pattern_ptr->data, reflags);
112                                 ret = regexec(&regex, line, 0, NULL, 0);
113                                 regfree(&regex);
114                         }
115                         if ((ret == 0 && !invert_search) || (ret == REG_NOMATCH && invert_search)) {
116
117                                 /* if we found a match but were told to be quiet, stop here and
118                                  * return success */
119                                 if (be_quiet)
120                                         exit(0);
121
122                                 /* keep track of matches */
123                                 nmatches++;
124
125                                 /* if we're just printing filenames, we stop after the first match */
126                                 if (print_files_with_matches)
127                                         break;
128
129                                 /* print the matched line */
130                                 if (print_match_counts == 0) {
131 #ifdef CONFIG_FEATURE_GREP_CONTEXT
132                                         int prevpos = (curpos == 0) ? lines_before - 1 : curpos - 1;
133
134                                         /* if we were told to print 'before' lines and there is at least
135                                          * one line in the circular buffer, print them */
136                                         if (lines_before && before_buf[prevpos] != NULL) {
137                                                 int first_buf_entry_line_num = linenum - lines_before;
138
139                                                 /* advance to the first entry in the circular buffer, and
140                                                  * figure out the line number is of the first line in the
141                                                  * buffer */
142                                                 idx = curpos;
143                                                 while (before_buf[idx] == NULL) {
144                                                         idx = (idx + 1) % lines_before;
145                                                         first_buf_entry_line_num++;
146                                                 }
147
148                                                 /* now print each line in the buffer, clearing them as we go */
149                                                 while (before_buf[idx] != NULL) {
150                                                         print_line(before_buf[idx], first_buf_entry_line_num, '-');
151                                                         free(before_buf[idx]);
152                                                         before_buf[idx] = NULL;
153                                                         idx = (idx + 1) % lines_before;
154                                                         first_buf_entry_line_num++;
155                                                 }
156                                         }
157
158                                         /* make a note that we need to print 'after' lines */
159                                         print_n_lines_after = lines_after;
160 #endif /* CONFIG_FEATURE_GREP_CONTEXT */ 
161                                         print_line(line, linenum, ':');
162                                 }
163                         }
164 #ifdef CONFIG_FEATURE_GREP_CONTEXT
165                         else { /* no match */
166                                 /* Add the line to the circular 'before' buffer */
167                                 if(lines_before) {
168                                         free(before_buf[curpos]);
169                                         before_buf[curpos] = bb_xstrdup(line);
170                                         curpos = (curpos + 1) % lines_before;
171                                 }
172                         }
173
174                         /* if we need to print some context lines after the last match, do so */
175                         if (print_n_lines_after && (last_line_printed != linenum)) {
176                                 print_line(line, linenum, '-');
177                                 print_n_lines_after--;
178                         }
179 #endif /* CONFIG_FEATURE_GREP_CONTEXT */ 
180                         pattern_ptr = pattern_ptr->link;
181                 } /* for */
182                 free(line);
183         }
184
185
186         /* special-case file post-processing for options where we don't print line
187          * matches, just filenames and possibly match counts */
188
189         /* grep -c: print [filename:]count, even if count is zero */
190         if (print_match_counts) {
191                 if (print_filename)
192                         printf("%s:", cur_file);
193                 if (print_files_with_matches && nmatches > 0)
194                         printf("1\n");
195                 else
196                     printf("%d\n", nmatches);
197         }
198
199         /* grep -l: print just the filename, but only if we grepped the line in the file  */
200         if (print_files_with_matches && nmatches > 0) {
201                 puts(cur_file);
202         }
203
204
205         /* remember if we matched */
206         if (nmatches != 0)
207                 matched = 1;
208 }
209
210 #if 0
211 static void add_pattern(char *restr)
212 {
213 //      regexes = xrealloc(regexes, sizeof(regex_t) * (++nregexes));
214 //      xregcomp(&regexes[nregexes-1], restr, reflags);
215         pattern_head = llist_add_to(pattern_head, restr);
216 }
217 #endif
218
219 static void     load_regexes_from_file(const char *filename)
220 {
221         char *line;
222         FILE *f = bb_xfopen(filename, "r");
223         while ((line = bb_get_chomped_line_from_file(f)) != NULL) {
224                 pattern_head = llist_add_to(pattern_head, line);
225         }
226 }
227
228
229 #ifdef CONFIG_FEATURE_CLEAN_UP
230 static void destroy_regexes(void)
231 {
232         llist_t *pattern_head_ptr;
233
234         if (pattern_head == NULL)
235                 return;
236
237         /* destroy all the elments in the pattern list */
238         while (pattern_head) {
239                 pattern_head_ptr = pattern_head;
240                 pattern_head = pattern_head->link;
241                 free(pattern_head_ptr->data);
242                 free(pattern_head_ptr);         
243         }
244 }
245 #endif
246
247
248 extern int grep_main(int argc, char **argv)
249 {
250         int opt;
251 #if defined (CONFIG_FEATURE_GREP_CONTEXT)
252         char *junk;
253 #endif
254
255 #ifdef CONFIG_FEATURE_CLEAN_UP
256         /* destroy command strings on exit */
257         atexit(destroy_regexes);
258 #endif
259
260 #ifdef CONFIG_FEATURE_GREP_EGREP_ALIAS
261         if (strcmp(bb_get_last_path_component(argv[0]), "egrep") == 0)
262                 reflags |= REG_EXTENDED;
263 #endif
264
265         /* do normal option parsing */
266         while ((opt = getopt(argc, argv, "iHhlnqvsce:f:F"
267 #ifdef CONFIG_FEATURE_GREP_CONTEXT
268 "A:B:C:"
269 #endif
270 #ifdef CONFIG_FEATURE_GREP_EGREP_ALIAS
271 "E"
272 #endif
273 )) > 0) {
274                 switch (opt) {
275                         case 'i':
276                                 reflags |= REG_ICASE;
277                                 break;
278                         case 'l':
279                                 print_files_with_matches++;
280                                 break;
281                         case 'H':
282                                 print_filename++;
283                                 break;
284                         case 'h':
285                                 print_filename--;
286                                 break;
287                         case 'n':
288                                 print_line_num++;
289                                 break;
290                         case 'q':
291                                 be_quiet++;
292                                 break;
293                         case 'v':
294                                 invert_search++;
295                                 break;
296                         case 's':
297                                 suppress_err_msgs++;
298                                 break;
299                         case 'c':
300                                 print_match_counts++;
301                                 break;
302                         case 'e':
303                                 pattern_head = llist_add_to(pattern_head, strdup(optarg));
304                                 break;
305 #ifdef CONFIG_FEATURE_GREP_EGREP_ALIAS
306                         case 'E':
307                                 reflags |= REG_EXTENDED;
308                                 break;
309 #endif
310                         case 'F':
311                                 fgrep_flag = 1;
312                                 break;
313                         case 'f':
314                                 load_regexes_from_file(optarg);
315                                 break;
316 #ifdef CONFIG_FEATURE_GREP_CONTEXT
317                         case 'A':
318                                 lines_after = strtoul(optarg, &junk, 10);
319                                 if(*junk != '\0')
320                                         bb_error_msg_and_die("invalid context length argument");
321                                 break;
322                         case 'B':
323                                 lines_before = strtoul(optarg, &junk, 10);
324                                 if(*junk != '\0')
325                                         bb_error_msg_and_die("invalid context length argument");
326                                 before_buf = (char **)xcalloc(lines_before, sizeof(char *));
327                                 break;
328                         case 'C':
329                                 lines_after = lines_before = strtoul(optarg, &junk, 10);
330                                 if(*junk != '\0')
331                                         bb_error_msg_and_die("invalid context length argument");
332                                 before_buf = (char **)xcalloc(lines_before, sizeof(char *));
333                                 break;
334 #endif /* CONFIG_FEATURE_GREP_CONTEXT */
335                         default:
336                                 bb_show_usage();
337                 }
338         }
339
340         /* if we didn't get a pattern from a -e and no command file was specified,
341          * argv[optind] should be the pattern. no pattern, no worky */
342         if (pattern_head == NULL) {
343                 if (argv[optind] == NULL)
344                         bb_show_usage();
345                 else {
346                         pattern_head = llist_add_to(pattern_head, strdup(argv[optind]));
347                         optind++;
348                 }
349         }
350
351         /* sanity checks */
352         if (print_match_counts || be_quiet || print_files_with_matches) {
353                 print_line_num = 0;
354 #ifdef CONFIG_FEATURE_GREP_CONTEXT
355                 lines_before = 0;
356                 lines_after = 0;
357 #endif
358         }
359
360         /* argv[(optind)..(argc-1)] should be names of file to grep through. If
361          * there is more than one file to grep, we will print the filenames */
362         if ((argc-1) - (optind) > 0)
363                 print_filename++;
364
365         /* If no files were specified, or '-' was specified, take input from
366          * stdin. Otherwise, we grep through all the files specified. */
367         if (argv[optind] == NULL || (strcmp(argv[optind], "-") == 0)) {
368                 grep_file(stdin);
369         }
370         else {
371                 int i;
372                 FILE *file;
373                 for (i = optind; i < argc; i++) {
374                         cur_file = argv[i];
375                         file = fopen(cur_file, "r");
376                         if (file == NULL) {
377                                 if (!suppress_err_msgs)
378                                         bb_perror_msg("%s", cur_file);
379                         }
380                         else {
381                                 grep_file(file);
382                                 fclose(file);
383                         }
384                 }
385         }
386
387         return !matched; /* invert return value 0 = success, 1 = failed */
388 }