source: MondoRescue/trunk/mindi-busybox/findutils/grep.c@ 904

Last change on this file since 904 was 821, checked in by Bruno Cornec, 18 years ago

Addition of busybox 1.2.1 as a mindi-busybox new package
This should avoid delivering binary files in mindi not built there (Fedora and Debian are quite serious about that)

File size: 11.8 KB
Line 
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, see the file LICENSE in this tarball.
9 */
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 */
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#include "busybox.h"
20#include <stdio.h>
21#include <stdlib.h>
22#include <getopt.h>
23#include <string.h>
24#include <errno.h>
25#include "xregex.h"
26
27
28/* options */
29static unsigned long opt;
30#define GREP_OPTS "lnqvscFiHhe:f:L"
31#define GREP_OPT_l (1<<0)
32#define PRINT_FILES_WITH_MATCHES (opt & GREP_OPT_l)
33#define GREP_OPT_n (1<<1)
34#define PRINT_LINE_NUM (opt & GREP_OPT_n)
35#define GREP_OPT_q (1<<2)
36#define BE_QUIET (opt & GREP_OPT_q)
37#define GREP_OPT_v (1<<3)
38typedef char invert_search_t;
39static invert_search_t invert_search;
40#define GREP_OPT_s (1<<4)
41#define SUPPRESS_ERR_MSGS (opt & GREP_OPT_s)
42#define GREP_OPT_c (1<<5)
43#define PRINT_MATCH_COUNTS (opt & GREP_OPT_c)
44#define GREP_OPT_F (1<<6)
45#define FGREP_FLAG (opt & GREP_OPT_F)
46#define GREP_OPT_i (1<<7)
47#define GREP_OPT_H (1<<8)
48#define GREP_OPT_h (1<<9)
49#define GREP_OPT_e (1<<10)
50#define GREP_OPT_f (1<<11)
51#define GREP_OPT_L (1<<12)
52#define PRINT_FILES_WITHOUT_MATCHES ((opt & GREP_OPT_L) != 0)
53#if ENABLE_FEATURE_GREP_CONTEXT
54#define GREP_OPT_CONTEXT "A:B:C"
55#define GREP_OPT_A (1<<13)
56#define GREP_OPT_B (1<<14)
57#define GREP_OPT_C (1<<15)
58#define GREP_OPT_E (1<<16)
59#else
60#define GREP_OPT_CONTEXT ""
61#define GREP_OPT_A (0)
62#define GREP_OPT_B (0)
63#define GREP_OPT_C (0)
64#define GREP_OPT_E (1<<13)
65#endif
66#if ENABLE_FEATURE_GREP_EGREP_ALIAS
67# define OPT_EGREP "E"
68#else
69# define OPT_EGREP ""
70#endif
71
72static int reflags;
73static int print_filename;
74
75#if ENABLE_FEATURE_GREP_CONTEXT
76static int lines_before;
77static int lines_after;
78static char **before_buf;
79static int last_line_printed;
80#endif /* ENABLE_FEATURE_GREP_CONTEXT */
81
82/* globals used internally */
83static llist_t *pattern_head; /* growable list of patterns to match */
84static char *cur_file; /* the current file we are reading */
85
86typedef struct GREP_LIST_DATA {
87 char *pattern;
88 regex_t preg;
89#define PATTERN_MEM_A 1
90#define COMPILED 2
91 int flg_mem_alocated_compiled;
92} grep_list_data_t;
93
94static void print_line(const char *line, int linenum, char decoration)
95{
96#if ENABLE_FEATURE_GREP_CONTEXT
97 /* possibly print the little '--' separator */
98 if ((lines_before || lines_after) && last_line_printed &&
99 last_line_printed < linenum - 1) {
100 puts("--");
101 }
102 last_line_printed = linenum;
103#endif
104 if (print_filename > 0)
105 printf("%s%c", cur_file, decoration);
106 if (PRINT_LINE_NUM)
107 printf("%i%c", linenum, decoration);
108 puts(line);
109}
110
111
112static int grep_file(FILE *file)
113{
114 char *line;
115 invert_search_t ret;
116 int linenum = 0;
117 int nmatches = 0;
118#if ENABLE_FEATURE_GREP_CONTEXT
119 int print_n_lines_after = 0;
120 int curpos = 0; /* track where we are in the circular 'before' buffer */
121 int idx = 0; /* used for iteration through the circular buffer */
122#endif /* ENABLE_FEATURE_GREP_CONTEXT */
123
124 while ((line = bb_get_chomped_line_from_file(file)) != NULL) {
125 llist_t *pattern_ptr = pattern_head;
126 grep_list_data_t * gl;
127
128 linenum++;
129 ret = 0;
130 while (pattern_ptr) {
131 gl = (grep_list_data_t *)pattern_ptr->data;
132 if (FGREP_FLAG) {
133 ret = strstr(line, gl->pattern) != NULL;
134 } else {
135 /*
136 * test for a postitive-assertion match (regexec returns success (0)
137 * and the user did not specify invert search), or a negative-assertion
138 * match (regexec returns failure (REG_NOMATCH) and the user specified
139 * invert search)
140 */
141 if(!(gl->flg_mem_alocated_compiled & COMPILED)) {
142 gl->flg_mem_alocated_compiled |= COMPILED;
143 xregcomp(&(gl->preg), gl->pattern, reflags);
144 }
145 ret |= regexec(&(gl->preg), line, 0, NULL, 0) == 0;
146 }
147 pattern_ptr = pattern_ptr->link;
148 } /* while (pattern_ptr) */
149
150 if ((ret ^ invert_search)) {
151
152 if (PRINT_FILES_WITH_MATCHES || BE_QUIET)
153 free(line);
154
155 /* if we found a match but were told to be quiet, stop here */
156 if (BE_QUIET || PRINT_FILES_WITHOUT_MATCHES)
157 return -1;
158
159 /* keep track of matches */
160 nmatches++;
161
162 /* if we're just printing filenames, we stop after the first match */
163 if (PRINT_FILES_WITH_MATCHES)
164 break;
165
166 /* print the matched line */
167 if (PRINT_MATCH_COUNTS == 0) {
168#if ENABLE_FEATURE_GREP_CONTEXT
169 int prevpos = (curpos == 0) ? lines_before - 1 : curpos - 1;
170
171 /* if we were told to print 'before' lines and there is at least
172 * one line in the circular buffer, print them */
173 if (lines_before && before_buf[prevpos] != NULL) {
174 int first_buf_entry_line_num = linenum - lines_before;
175
176 /* advance to the first entry in the circular buffer, and
177 * figure out the line number is of the first line in the
178 * buffer */
179 idx = curpos;
180 while (before_buf[idx] == NULL) {
181 idx = (idx + 1) % lines_before;
182 first_buf_entry_line_num++;
183 }
184
185 /* now print each line in the buffer, clearing them as we go */
186 while (before_buf[idx] != NULL) {
187 print_line(before_buf[idx], first_buf_entry_line_num, '-');
188 free(before_buf[idx]);
189 before_buf[idx] = NULL;
190 idx = (idx + 1) % lines_before;
191 first_buf_entry_line_num++;
192 }
193 }
194
195 /* make a note that we need to print 'after' lines */
196 print_n_lines_after = lines_after;
197#endif
198 print_line(line, linenum, ':');
199 }
200 }
201#if ENABLE_FEATURE_GREP_CONTEXT
202 else { /* no match */
203 /* Add the line to the circular 'before' buffer */
204 if(lines_before) {
205 free(before_buf[curpos]);
206 before_buf[curpos] = bb_xstrdup(line);
207 curpos = (curpos + 1) % lines_before;
208 }
209 }
210
211 /* if we need to print some context lines after the last match, do so */
212 if (print_n_lines_after && (last_line_printed != linenum)) {
213 print_line(line, linenum, '-');
214 print_n_lines_after--;
215 }
216#endif /* ENABLE_FEATURE_GREP_CONTEXT */
217 free(line);
218 }
219
220
221 /* special-case file post-processing for options where we don't print line
222 * matches, just filenames and possibly match counts */
223
224 /* grep -c: print [filename:]count, even if count is zero */
225 if (PRINT_MATCH_COUNTS) {
226 if (print_filename > 0)
227 printf("%s:", cur_file);
228 printf("%d\n", nmatches);
229 }
230
231 /* grep -l: print just the filename, but only if we grepped the line in the file */
232 if (PRINT_FILES_WITH_MATCHES && nmatches > 0) {
233 puts(cur_file);
234 }
235
236 /* grep -L: print just the filename, but only if we didn't grep the line in the file */
237 if (PRINT_FILES_WITHOUT_MATCHES && nmatches == 0) {
238 puts(cur_file);
239 }
240
241 return nmatches;
242}
243
244#if ENABLE_FEATURE_CLEAN_UP
245#define new_grep_list_data(p, m) add_grep_list_data(p, m)
246static char * add_grep_list_data(char *pattern, int flg_used_mem)
247#else
248#define new_grep_list_data(p, m) add_grep_list_data(p)
249static char * add_grep_list_data(char *pattern)
250#endif
251{
252 grep_list_data_t *gl = xmalloc(sizeof(grep_list_data_t));
253 gl->pattern = pattern;
254#if ENABLE_FEATURE_CLEAN_UP
255 gl->flg_mem_alocated_compiled = flg_used_mem;
256#else
257 gl->flg_mem_alocated_compiled = 0;
258#endif
259 return (char *)gl;
260}
261
262
263static void load_regexes_from_file(llist_t *fopt)
264{
265 char *line;
266 FILE *f;
267
268 while(fopt) {
269 llist_t *cur = fopt;
270 char *ffile = cur->data;
271
272 fopt = cur->link;
273 free(cur);
274 f = bb_xfopen(ffile, "r");
275 while ((line = bb_get_chomped_line_from_file(f)) != NULL) {
276 llist_add_to(&pattern_head,
277 new_grep_list_data(line, PATTERN_MEM_A));
278 }
279 }
280}
281
282
283int grep_main(int argc, char **argv)
284{
285 FILE *file;
286 int matched;
287 llist_t *fopt = NULL;
288 int error_open_count = 0;
289
290 /* do normal option parsing */
291#if ENABLE_FEATURE_GREP_CONTEXT
292 {
293 char *junk;
294 char *slines_after;
295 char *slines_before;
296 char *Copt;
297
298 bb_opt_complementally = "H-h:e::f::C-AB";
299 opt = bb_getopt_ulflags(argc, argv,
300 GREP_OPTS GREP_OPT_CONTEXT OPT_EGREP,
301 &pattern_head, &fopt,
302 &slines_after, &slines_before, &Copt);
303
304 if(opt & GREP_OPT_C) {
305 /* C option unseted A and B options, but next -A or -B
306 may be ovewrite own option */
307 if(!(opt & GREP_OPT_A)) /* not overwtited */
308 slines_after = Copt;
309 if(!(opt & GREP_OPT_B)) /* not overwtited */
310 slines_before = Copt;
311 opt |= GREP_OPT_A|GREP_OPT_B; /* set for parse now */
312 }
313 if(opt & GREP_OPT_A) {
314 lines_after = strtoul(slines_after, &junk, 10);
315 if(*junk != '\0')
316 bb_error_msg_and_die(bb_msg_invalid_arg, slines_after, "-A");
317 }
318 if(opt & GREP_OPT_B) {
319 lines_before = strtoul(slines_before, &junk, 10);
320 if(*junk != '\0')
321 bb_error_msg_and_die(bb_msg_invalid_arg, slines_before, "-B");
322 }
323 /* sanity checks after parse may be invalid numbers ;-) */
324 if ((opt & (GREP_OPT_c|GREP_OPT_q|GREP_OPT_l|GREP_OPT_L))) {
325 opt &= ~GREP_OPT_n;
326 lines_before = 0;
327 lines_after = 0;
328 } else if(lines_before > 0)
329 before_buf = (char **)xcalloc(lines_before, sizeof(char *));
330 }
331#else
332 /* with auto sanity checks */
333 bb_opt_complementally = "H-h:e::f::c-n:q-n:l-n";
334 opt = bb_getopt_ulflags(argc, argv, GREP_OPTS OPT_EGREP,
335 &pattern_head, &fopt);
336#endif
337 invert_search = (opt & GREP_OPT_v) != 0; /* 0 | 1 */
338
339 if(opt & GREP_OPT_H)
340 print_filename++;
341 if(opt & GREP_OPT_h)
342 print_filename--;
343 if (pattern_head != NULL) {
344 /* convert char *argv[] to grep_list_data_t */
345 llist_t *cur;
346
347 for(cur = pattern_head; cur; cur = cur->link)
348 cur->data = new_grep_list_data(cur->data, 0);
349 }
350 if(opt & GREP_OPT_f)
351 load_regexes_from_file(fopt);
352
353 if(ENABLE_FEATURE_GREP_FGREP_ALIAS && bb_applet_name[0] == 'f')
354 opt |= GREP_OPT_F;
355
356 if(ENABLE_FEATURE_GREP_EGREP_ALIAS &&
357 (bb_applet_name[0] == 'e' || (opt & GREP_OPT_E)))
358 reflags = REG_EXTENDED | REG_NOSUB;
359 else
360 reflags = REG_NOSUB;
361
362 if(opt & GREP_OPT_i)
363 reflags |= REG_ICASE;
364
365 argv += optind;
366 argc -= optind;
367
368 /* if we didn't get a pattern from a -e and no command file was specified,
369 * argv[optind] should be the pattern. no pattern, no worky */
370 if (pattern_head == NULL) {
371 if (*argv == NULL)
372 bb_show_usage();
373 else {
374 char *pattern = new_grep_list_data(*argv++, 0);
375
376 llist_add_to(&pattern_head, pattern);
377 argc--;
378 }
379 }
380
381 /* argv[(optind)..(argc-1)] should be names of file to grep through. If
382 * there is more than one file to grep, we will print the filenames */
383 if (argc > 1) {
384 print_filename++;
385
386 /* If no files were specified, or '-' was specified, take input from
387 * stdin. Otherwise, we grep through all the files specified. */
388 } else if (argc == 0) {
389 argc++;
390 }
391 matched = 0;
392 while (argc--) {
393 cur_file = *argv++;
394 if(!cur_file || (*cur_file == '-' && !cur_file[1])) {
395 cur_file = "(standard input)";
396 file = stdin;
397 } else {
398 file = fopen(cur_file, "r");
399 }
400 if (file == NULL) {
401 if (!SUPPRESS_ERR_MSGS)
402 bb_perror_msg("%s", cur_file);
403 error_open_count++;
404 } else {
405 matched += grep_file(file);
406 if(matched < 0) {
407 /* we found a match but were told to be quiet, stop here and
408 * return success */
409 break;
410 }
411 fclose(file);
412 }
413 }
414
415 /* destroy all the elments in the pattern list */
416 if (ENABLE_FEATURE_CLEAN_UP) {
417 while (pattern_head) {
418 llist_t *pattern_head_ptr = pattern_head;
419 grep_list_data_t *gl =
420 (grep_list_data_t *)pattern_head_ptr->data;
421
422 pattern_head = pattern_head->link;
423 if((gl->flg_mem_alocated_compiled & PATTERN_MEM_A))
424 free(gl->pattern);
425 if((gl->flg_mem_alocated_compiled & COMPILED))
426 regfree(&(gl->preg));
427 free(pattern_head_ptr);
428 }
429 }
430 /* 0 = success, 1 = failed, 2 = error */
431 /* If the -q option is specified, the exit status shall be zero
432 * if an input line is selected, even if an error was detected. */
433 if(BE_QUIET && matched)
434 return 0;
435 if(error_open_count)
436 return 2;
437 return !matched; /* invert return value 0 = success, 1 = failed */
438}
Note: See TracBrowser for help on using the repository browser.