OSDN Git Service

grep doesn't allocate enough space
[android-x86/external-toybox.git] / toys / posix / grep.c
1 /* grep.c - print lines what match given regular expression
2  *
3  * Copyright 2013 CE Strake <strake888 at gmail.com>
4  *
5  * See http://pubs.opengroup.org/onlinepubs/9699919799/utilities/grep.html
6
7 USE_GREP(NEWTOY(grep, "EFHabhinorsvwclqe*f*m#x[!wx][!EFw]", TOYFLAG_BIN))
8 USE_GREP(OLDTOY(egrep, grep, OPTSTR_grep, TOYFLAG_BIN))
9 USE_GREP(OLDTOY(fgrep, grep, OPTSTR_grep, TOYFLAG_BIN))
10
11 config GREP
12   bool "grep"
13   default y
14   help
15     usage: grep [-EFivwcloqsHbhn] [-m MAX] [-e REGEX]... [-f REGFILE] [FILE]...
16
17     Show lines matching regular expressions. If no -e, first argument is
18     regular expression to match. With no files (or "-" filename) read stdin.
19     Returns 0 if matched, 1 if no match found.
20
21     -e  Regex to match. (May be repeated.)
22     -f  File containing regular expressions to match.
23
24     match type:
25     -E  extended regex syntax    -F  fixed (match literal string)
26     -i  case insensitive         -m  stop after this many lines matched
27     -r  recursive (on dir)       -v  invert match
28     -w  whole word (implies -E)  -x  whole line
29
30     display modes: (default: matched line)
31     -c  count of matching lines  -l  show matching filenames
32     -o  only matching part       -q  quiet (errors only)
33     -s  silent (no error msg)    
34
35     prefix modes (default: filename if checking more than 1 file)
36     -H  force filename           -b  byte offset of match
37     -h  hide filename            -n  line number of match
38 */
39
40 #define FOR_grep
41 #include "toys.h"
42 #include <regex.h>
43
44 GLOBALS(
45   long m;
46   struct arg_list *f;
47   struct arg_list *e;
48
49   struct arg_list *regex;
50 )
51
52 static void do_grep(int fd, char *name)
53 {
54   FILE *file = fdopen(fd, "r");
55   long offset = 0;
56   int lcount = 0, mcount = 0, which = toys.optflags & FLAG_w ? 2 : 0;
57
58   if (!fd) name = "(standard input)";
59
60   if (!file) {
61     perror_msg("%s", name);
62     return;
63   }
64
65   for (;;) {
66     char *line = 0, *start;
67     regmatch_t matches[3];
68     size_t unused;
69     long len;
70     int mmatch = 0;
71
72     lcount++;
73     if (0 > (len = getline(&line, &unused, file))) break;
74     if (line[len-1] == '\n') line[len-1] = 0;
75
76     start = line;
77
78     for (;;)
79     {
80       int rc = 0, skip = 0;
81
82       if (toys.optflags & FLAG_F) {
83         struct arg_list *seek, fseek;
84         char *s = 0;
85
86         for (seek = TT.e; seek; seek = seek->next) {
87           if (toys.optflags & FLAG_x) {
88             int i = (toys.optflags & FLAG_i);
89
90             if ((i ? strcasecmp : strcmp)(seek->arg, line)) s = line;
91           } else if (!*seek->arg) {
92             seek = &fseek;
93             fseek.arg = s = line;
94             break;
95           }
96           if (toys.optflags & FLAG_i) {
97             long ll = strlen(seek->arg);;
98
99             // Alas, posix hasn't got strcasestr()
100             for (s = line; *s; s++) if (!strncasecmp(s, seek->arg, ll)) break;
101             if (!*s) s = 0;
102           } else s = strstr(line, seek->arg);
103           if (s) break;
104         }
105
106         if (s) {
107           matches[which].rm_so = (s-line);
108           skip = matches[which].rm_eo = (s-line)+strlen(seek->arg);
109         } else rc = 1;
110       } else {
111         rc = regexec((regex_t *)toybuf, start, 3, matches,
112                      start==line ? 0 : REG_NOTBOL);
113         skip = matches[which].rm_eo;
114       }
115
116       if (toys.optflags & FLAG_x)
117         if (matches[which].rm_so || line[matches[which].rm_eo]) rc = 1;
118
119       if (toys.optflags & FLAG_v) {
120         if (toys.optflags & FLAG_o) {
121           if (rc) skip = matches[which].rm_eo = strlen(start);
122           else if (!matches[which].rm_so) {
123             start += skip;
124             continue;
125           } else matches[which].rm_eo = matches[which].rm_so;
126         } else {
127           if (!rc) break;
128           matches[which].rm_eo = strlen(start);
129         }
130         matches[which].rm_so = 0;
131       } else if (rc) break;
132
133       mmatch++;
134       toys.exitval = 0;
135       if (toys.optflags & FLAG_q) xexit();
136       if (toys.optflags & FLAG_l) {
137         printf("%s\n", name);
138         free(line);
139         fclose(file);
140         return;
141       }
142       if (toys.optflags & FLAG_o)
143         if (matches[which].rm_eo == matches[which].rm_so)
144           break;
145
146       if (!(toys.optflags & FLAG_c)) {
147         if (toys.optflags & FLAG_H) printf("%s:", name);
148         if (toys.optflags & FLAG_n) printf("%d:", lcount);
149         if (toys.optflags & FLAG_b)
150           printf("%ld:", offset + (start-line) +
151               ((toys.optflags & FLAG_o) ? matches[which].rm_so : 0));
152         if (!(toys.optflags & FLAG_o)) xputs(line);
153         else {
154           xprintf("%.*s\n", matches[which].rm_eo - matches[which].rm_so,
155                   start + matches[which].rm_so);
156         }
157       }
158
159       start += skip;
160       if (!(toys.optflags & FLAG_o) || !*start) break;
161     }
162     offset += len;
163
164     free(line);
165
166     if (mmatch) mcount++;
167     if ((toys.optflags & FLAG_m) && mcount >= TT.m) break;
168   }
169
170   if (toys.optflags & FLAG_c) {
171     if (toys.optflags & FLAG_H) printf("%s:", name);
172     xprintf("%d\n", mcount);
173   }
174
175   // loopfiles will also close the fd, but this frees an (opaque) struct.
176   fclose(file);
177 }
178
179 static void parse_regex(void)
180 {
181   struct arg_list *al, *new, *list = NULL;
182   long len = 0;
183   char *s, *ss;
184
185   // Add all -f lines to -e list. (Yes, this is leaking allocation context for
186   // exit to free. Not supporting nofork for this command any time soon.)
187   al = TT.f ? TT.f : TT.e;
188   while (al) {
189     if (TT.f) s = ss = xreadfile(al->arg);
190     else s = ss = al->arg;
191
192     do {
193       ss = strchr(s, '\n');
194       if (ss) *(ss++) = 0;
195       new = xmalloc(sizeof(struct arg_list));
196       new->next = list;
197       new->arg = s;
198       list = new;
199       s = ss;
200     } while (ss && *s);
201     al = al->next;
202     if (!al && TT.f) {
203       TT.f = 0;
204       al = TT.e;
205     }
206   }
207   TT.e = list;
208
209   if (!(toys.optflags & FLAG_F)) {
210     int w = toys.optflags & FLAG_w;
211     char *regstr;
212
213     // Convert strings to one big regex
214     if (w) len = 36;
215     for (al = TT.e; al; al = al->next)
216       len += strlen(al->arg)+1+!(toys.optflags & FLAG_E);
217
218     regstr = s = xmalloc(len);
219     if (w) s = stpcpy(s, "(^|[^_[:alnum:]])(");
220     for (al = TT.e; al; al = al->next) {
221       s = stpcpy(s, al->arg);
222       if (!(toys.optflags & FLAG_E)) *(s++) = '\\';
223       *(s++) = '|';
224     }
225     *(s-=(1+!(toys.optflags & FLAG_E))) = 0;
226     if (w) strcpy(s, ")($|[^_[:alnum:]])");
227
228     w = regcomp((regex_t *)toybuf, regstr,
229                 ((toys.optflags & FLAG_E) ? REG_EXTENDED : 0) |
230                 ((toys.optflags & FLAG_i) ? REG_ICASE    : 0));
231
232     if (w) {
233       regerror(w, (regex_t *)toybuf, toybuf+sizeof(regex_t),
234                sizeof(toybuf)-sizeof(regex_t));
235       error_exit("bad REGEX: %s", toybuf);
236     }
237   }
238 }
239
240 static int do_grep_r(struct dirtree *new)
241 {
242   char *name;
243
244   if (new->parent && !dirtree_notdotdot(new)) return 0;
245   if (S_ISDIR(new->st.st_mode)) return DIRTREE_RECURSE;
246
247   // "grep -r onefile" doesn't show filenames, but "grep -r onedir" should.
248   if (new->parent && !(toys.optflags & FLAG_h)) toys.optflags |= FLAG_H;
249
250   name = dirtree_path(new, 0);
251   do_grep(openat(dirtree_parentfd(new), new->name, 0), name);
252   free(name);
253
254   return 0;
255 }
256
257 void grep_main(void)
258 {
259   char **ss;
260
261   // Handle egrep and fgrep
262   if (*toys.which->name == 'e' || (toys.optflags & FLAG_w))
263     toys.optflags |= FLAG_E;
264   if (*toys.which->name == 'f') toys.optflags |= FLAG_F;
265
266   if (!TT.e && !TT.f) {
267     if (!*toys.optargs) error_exit("no REGEX");
268     TT.e = xzalloc(sizeof(struct arg_list));
269     TT.e->arg = *(toys.optargs++);
270     toys.optc--;
271   }
272
273   parse_regex();
274
275   if (!(toys.optflags & FLAG_h) && toys.optc>1) toys.optflags |= FLAG_H;
276
277   toys.exitval = 1;
278   if (toys.optflags & FLAG_s) {
279     close(2);
280     xopen("/dev/null", O_RDWR);
281   }
282
283   if (toys.optflags & FLAG_r) {
284     for (ss=toys.optargs; *ss; ss++) {
285       if (!strcmp(*ss, "-")) do_grep(0, *ss);
286       else dirtree_read(*ss, do_grep_r);
287     }
288   } else loopfiles_rw(toys.optargs, O_RDONLY, 0, 1, do_grep);
289 }