• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* grep.c - show lines matching regular expressions
2  *
3  * Copyright 2013 CE Strake <strake888 at gmail.com>
4  *
5  * See http://pubs.opengroup.org/onlinepubs/9699919799/utilities/grep.html
6  *
7  * Posix doesn't even specify -r: too many deviations to document.
8  * TODO: -i is only ascii case insensitive, not unicode.
9 
10 USE_GREP(NEWTOY(grep, "(line-buffered)(color):;(exclude-dir)*S(exclude)*M(include)*ZzEFHIab(byte-offset)h(no-filename)ino(only-matching)rRsvwc(count)L(files-without-match)l(files-with-matches)q(quiet)(silent)e*f*C#B#A#m#x[!wx][!EF]", TOYFLAG_BIN|TOYFLAG_ARGFAIL(2)|TOYFLAG_LINEBUF))
11 USE_EGREP(OLDTOY(egrep, grep, TOYFLAG_BIN|TOYFLAG_ARGFAIL(2)|TOYFLAG_LINEBUF))
12 USE_FGREP(OLDTOY(fgrep, grep, TOYFLAG_BIN|TOYFLAG_ARGFAIL(2)|TOYFLAG_LINEBUF))
13 
14 config GREP
15   bool "grep"
16   default y
17   help
18     usage: grep [-EFrivwcloqsHbhn] [-ABC NUM] [-m MAX] [-e REGEX]... [-MS PATTERN]... [-f REGFILE] [FILE]...
19 
20     Show lines matching regular expressions. If no -e, first argument is
21     regular expression to match. With no files (or "-" filename) read stdin.
22     Returns 0 if matched, 1 if no match found, 2 for command errors.
23 
24     -e  Regex to match. (May be repeated.)
25     -f  File listing regular expressions to match.
26 
27     file search:
28     -r  Recurse into subdirectories (defaults FILE to ".")
29     -R  Recurse into subdirectories and symlinks to directories
30     -M  Match filename pattern (--include)
31     -S  Skip filename pattern (--exclude)
32     --exclude-dir=PATTERN  Skip directory pattern
33     -I  Ignore binary files
34 
35     match type:
36     -A  Show NUM lines after     -B  Show NUM lines before match
37     -C  NUM lines context (A+B)  -E  extended regex syntax
38     -F  fixed (literal match)    -a  always text (not binary)
39     -i  case insensitive         -m  match MAX many lines
40     -v  invert match             -w  whole word (implies -E)
41     -x  whole line               -z  input NUL terminated
42 
43     display modes: (default: matched line)
44     -L  filenames with no match  -Z  output is NUL terminated
45     -c  count of matching lines  -l  filenames with a match
46     -o  only matching part       -q  quiet (errors only)
47     -s  silent (no error msg)
48 
49     output prefix (default: filename if checking more than 1 file)
50     -H  force filename           -b  byte offset of match
51     -h  hide filename            -n  line number of match
52 
53 config EGREP
54   bool
55   default y
56   depends on GREP
57 
58 config FGREP
59   bool
60   default y
61   depends on GREP
62 */
63 
64 #define FOR_grep
65 #include "toys.h"
66 
67 GLOBALS(
68   long m, A, B, C;
69   struct arg_list *f, *e, *M, *S, *exclude_dir;
70   char *color;
71 
72   char *purple, *cyan, *red, *green, *grey;
73   struct double_list *reg;
74   int found, tried, delim;
75   struct arg_list *fixed[256];
76 )
77 
78 struct reg {
79   struct reg *next, *prev;
80   int rc;
81   regex_t r;
82   regmatch_t m;
83 };
84 
numdash(long num,char dash)85 static void numdash(long num, char dash)
86 {
87   printf("%s%ld%s%c", TT.green, num, TT.cyan, dash);
88 }
89 
90 // Emit line with various potential prefixes and delimiter
outline(char * line,char dash,char * name,long lcount,long bcount,unsigned trim)91 static void outline(char *line, char dash, char *name, long lcount, long bcount,
92   unsigned trim)
93 {
94   if (!trim && FLAG(o)) return;
95   if (name && FLAG(H)) printf("%s%s%s%c", TT.purple, name, TT.cyan, dash);
96   if (FLAG(c)) xprintf("%s%ld%c", TT.grey, lcount, TT.delim);
97   else if (lcount && FLAG(n)) numdash(lcount, dash);
98   if (bcount && FLAG(b)) numdash(bcount-1, dash);
99   if (line) {
100     if (FLAG(color)) xputsn(FLAG(o) ? TT.red : TT.grey);
101     // support embedded NUL bytes in output
102     xputsl(line, trim);
103     xputc(TT.delim);
104   }
105 }
106 
107 // Show matches in one file
do_grep(int fd,char * name)108 static void do_grep(int fd, char *name)
109 {
110   long lcount = 0, mcount = 0, offset = 0, after = 0, before = 0;
111   struct double_list *dlb = 0;
112   char *bars = 0;
113   FILE *file;
114   int bin = 0;
115 
116   if (!FLAG(r)) TT.tried++;
117   if (!fd) name = "(standard input)";
118 
119   // Only run binary file check on lseekable files.
120   if (!FLAG(a) && !lseek(fd, 0, SEEK_CUR)) {
121     char buf[256];
122     int len, i = 0;
123     unsigned wc;
124 
125     // If the first 256 bytes don't parse as utf8, call it binary.
126     if (0<(len = read(fd, buf, 256))) {
127       lseek(fd, -len, SEEK_CUR);
128       while (i<len) {
129         bin = utf8towc(&wc, buf+i, len-i);
130         if (bin == -2) i = len;
131         if (bin<1) break;
132         i += bin;
133       }
134       bin = i!=len;
135     }
136     if (bin && FLAG(I)) return;
137   }
138 
139   if (!(file = fdopen(fd, "r"))) return perror_msg("%s", name);
140 
141   // Loop through lines of input
142   for (;;) {
143     char *line = 0, *start, *ss, *pp;
144     struct reg *shoe;
145     size_t ulen;
146     long len;
147     int matched = 0, rc = 1, move = 0, ii;
148 
149     // get next line, check and trim delimiter
150     lcount++;
151     errno = 0;
152     ulen = len = getdelim(&line, &ulen, TT.delim, file);
153     if (len == -1 && errno) perror_msg("%s", name);
154     if (len<1) break;
155     if (line[ulen-1] == TT.delim) line[--ulen] = 0;
156 
157     // Prepare for next line
158     start = line;
159     for (shoe = (void *)TT.reg; shoe; shoe = shoe->next) shoe->rc = 0;
160 
161     // Loop to handle multiple matches in same line
162     do {
163       regmatch_t *mm = (void *)toybuf;
164       struct arg_list *seek;
165 
166       mm->rm_so = mm->rm_eo = 0;
167       rc = 1;
168 
169       // Handle "fixed" (literal) matches (if any)
170       if (TT.e && *start) for (ss = start; ss-line<ulen; ss++) {
171         ii = FLAG(i) ? toupper(*ss) : *ss;
172         for (seek = TT.fixed[ii]; seek; seek = seek->next) {
173           if (*(pp = seek->arg)=='^' && !FLAG(F)) {
174             if (ss!=start) continue;
175             pp++;
176           }
177           for (ii = 0; pp[ii] && ss[ii]; ii++) {
178             if (!FLAG(F)) {
179               if (pp[ii]=='.') continue;
180               if (pp[ii]=='\\' && pp[ii+1]) pp++;
181               else if (pp[ii]=='$' && !pp[ii+1]) break;
182             }
183             if (FLAG(i)) {
184               if (toupper(pp[ii])!=toupper(ss[ii])) break;
185             } else if (pp[ii]!=ss[ii]) break;
186           }
187           if (pp[ii] && (pp[ii]!='$' || pp[ii+1] || ss[ii])) continue;
188           mm->rm_eo = (mm->rm_so = ss-start)+ii;
189           rc = 0;
190 
191           goto got;
192         }
193         if (FLAG(x)) break;
194       }
195 
196       // Empty pattern always matches
197       if (rc && *TT.fixed && !FLAG(o)) rc = 0;
198 got:
199       // Handle regex matches (if any)
200       for (shoe = (void *)TT.reg; shoe; shoe = shoe->next) {
201         // Do we need to re-check this regex?
202         if (!shoe->rc) {
203           shoe->m.rm_so -= move;
204           shoe->m.rm_eo -= move;
205           if (!matched || shoe->m.rm_so<0)
206             shoe->rc = regexec0(&shoe->r, start, ulen-(start-line), 1,
207                                 &shoe->m, start==line ? 0 : REG_NOTBOL);
208         }
209 
210         // If we got a match, is it a _better_ match?
211         if (!shoe->rc && (rc || shoe->m.rm_so < mm->rm_so ||
212             (shoe->m.rm_so == mm->rm_so && shoe->m.rm_eo >= mm->rm_eo)))
213         {
214           mm = &shoe->m;
215           rc = 0;
216         }
217       }
218 
219       if (!rc && FLAG(o) && !mm->rm_eo && ulen>start-line) {
220         move = 1;
221         continue;
222       }
223 
224       if (!rc && FLAG(x) && (mm->rm_so || ulen-(start-line)!=mm->rm_eo)) rc = 1;
225 
226       if (!rc && FLAG(w)) {
227         char c = 0;
228 
229         if ((start+mm->rm_so)!=line) {
230           c = start[mm->rm_so-1];
231           if (!isalnum(c) && c != '_') c = 0;
232         }
233         if (!c) {
234           c = start[mm->rm_eo];
235           if (!isalnum(c) && c != '_') c = 0;
236         }
237         if (c) {
238           move = mm->rm_so+1;
239           continue;
240         }
241       }
242 
243       if (FLAG(v)) {
244         if (FLAG(o)) {
245           if (rc) mm->rm_eo = ulen-(start-line);
246           else if (!mm->rm_so) {
247             move = mm->rm_eo;
248             continue;
249           } else mm->rm_eo = mm->rm_so;
250         } else {
251           if (!rc) break;
252           mm->rm_eo = ulen-(start-line);
253         }
254         mm->rm_so = 0;
255       } else if (rc) break;
256 
257       // At least one line we didn't print since match while -ABC active
258       if (bars) {
259         xputs(bars);
260         bars = 0;
261       }
262       matched++;
263       TT.found = 1;
264 
265       // Are we NOT showing the matching text?
266       if (FLAG(q)) {
267         toys.exitval = 0;
268         xexit();
269       }
270       if (FLAG(L) || FLAG(l)) {
271         if (FLAG(l)) xprintf("%s%c", name, '\n'*!FLAG(Z));
272         free(line);
273         fclose(file);
274         return;
275       }
276 
277       if (!FLAG(c)) {
278         long bcount = 1 + offset + (start-line) + (FLAG(o) ? mm->rm_so : 0);
279 
280         if (bin) printf("Binary file %s matches\n", name);
281         else if (FLAG(o))
282           outline(start+mm->rm_so, ':', name, lcount, bcount,
283                   mm->rm_eo-mm->rm_so);
284         else {
285           while (dlb) {
286             struct double_list *dl = dlist_pop(&dlb);
287             unsigned *uu = (void *)(dl->data+(strlen(dl->data)|3)+1);
288 
289             outline(dl->data, '-', name, lcount-before, uu[0]+1, uu[1]);
290             free(dl->data);
291             free(dl);
292             before--;
293           }
294 
295           if (matched==1)
296             outline(FLAG(color) ? 0 : line, ':', name, lcount, bcount, ulen);
297           if (FLAG(color)) {
298             xputsn(TT.grey);
299             if (mm->rm_so) xputsl(start, mm->rm_so);
300             xputsn(TT.red);
301             xputsl(start+mm->rm_so, mm->rm_eo-mm->rm_so);
302           }
303 
304           if (TT.A) after = TT.A+1;
305         }
306       }
307 
308       if (mm->rm_so == (move = mm->rm_eo)) break;
309     } while (*(start += move));
310     offset += len;
311 
312     if (matched) {
313       // Finish off pending line color fragment.
314       if (FLAG(color) && !FLAG(o)) {
315         xputsn(TT.grey);
316         if (ulen > start-line) xputsl(start, ulen-(start-line));
317         xputc(TT.delim);
318       }
319       mcount++;
320     } else {
321       int discard = (after || TT.B);
322 
323       if (after && --after) {
324         outline(line, '-', name, lcount, 0, ulen);
325         discard = 0;
326       }
327       if (discard && TT.B) {
328         unsigned *uu, ul = (ulen|3)+1;
329 
330         line = xrealloc(line, ul+8);
331         uu = (void *)(line+ul);
332         uu[0] = offset-len;
333         uu[1] = ulen;
334         dlist_add(&dlb, line);
335         line = 0;
336         if (++before>TT.B) {
337           struct double_list *dl;
338 
339           dl = dlist_pop(&dlb);
340           free(dl->data);
341           free(dl);
342           before--;
343         } else discard = 0;
344       }
345       // If we discarded a line while displaying context, show bars before next
346       // line (but don't show them now in case that was last match in file)
347       if (discard && mcount) bars = "--";
348     }
349     free(line);
350 
351     if (FLAG(m) && mcount >= TT.m) break;
352   }
353 
354   if (FLAG(L)) xprintf("%s%c", name, TT.delim);
355   else if (FLAG(c)) outline(0, ':', name, mcount, 0, 1);
356 
357   // loopfiles will also close the fd, but this frees an (opaque) struct.
358   fclose(file);
359   while (dlb) {
360     struct double_list *dl = dlist_pop(&dlb);
361 
362     free(dl->data);
363     free(dl);
364   }
365 }
366 
lensort(struct arg_list ** a,struct arg_list ** b)367 static int lensort(struct arg_list **a, struct arg_list **b)
368 {
369   long la = strlen((*a)->arg), lb = strlen((*b)->arg);
370 
371   if (la<lb) return -1;
372   if (la>lb) return 1;
373 
374   return 0;
375 }
376 
parse_regex(void)377 static void parse_regex(void)
378 {
379   struct arg_list *al, *new, *list = NULL, **last;
380   char *s, *ss, *special = "\\.^$[()|*+?{";
381   int len, ii, key;
382 
383   // Add all -f lines to -e list. (Yes, this is leaking allocation context for
384   // exit to free. Not supporting nofork for this command any time soon.)
385   al = TT.f ? TT.f : TT.e;
386   while (al) {
387     if (TT.f) {
388       if (!*(s = xreadfile(al->arg, 0, 0))) {
389         free(s);
390         s = 0;
391       } else if (*(ss = s+strlen(s)-1)=='\n') *ss = 0;
392     } else s = al->arg;
393 
394     // Advance, when we run out of -f switch to -e.
395     al = al->next;
396     if (!al && TT.f) {
397       TT.f = 0;
398       al = TT.e;
399     }
400     if (!s) continue;
401 
402     // NOTE: even with -z, -f is still \n delimited. Blank line = match all
403     // Split lines at \n, add individual lines to new list.
404     do {
405       if ((ss = strchr(s, '\n'))) *(ss++) = 0;
406       new = xmalloc(sizeof(struct arg_list));
407       new->next = list;
408       new->arg = s;
409       list = new;
410       s = ss;
411     } while (s);
412   }
413   TT.e = list;
414 
415   // Convert to regex where appropriate
416   for (last = &TT.e; *last;) {
417     // Can we use the fast path?
418     s = (*last)->arg;
419     if ('.'!=*s && !FLAG(F) && strcmp(s, "^$")) for (; *s; s++) {
420       if (*s=='\\') {
421         if (!s[1] || !strchr(special, *++s)) break;
422         if (!FLAG(E) && *s=='(') break;
423       } else if (*s>127 || strchr(special+4, *s)) break;
424     }
425 
426     // Add entry to fast path (literal-ish match) or slow path (regexec)
427     if (!*s || FLAG(F)) last = &((*last)->next);
428     else {
429       struct reg *shoe;
430 
431       dlist_add_nomalloc(&TT.reg, (void *)(shoe = xmalloc(sizeof(struct reg))));
432       xregcomp(&shoe->r, (*last)->arg, REG_EXTENDED*FLAG(E)|REG_ICASE*FLAG(i));
433       al = *last;
434       *last = (*last)->next;
435       free(al);
436     }
437   }
438   dlist_terminate(TT.reg);
439 
440   // Sort fast path patterns into buckets by first character
441   for (al = TT.e; al; al = new) {
442     new = al->next;
443     if (FLAG(F)) key = 0;
444     else {
445       key = '^'==*al->arg;
446       if ('\\'==al->arg[key]) key++;
447       else if ('$'==al->arg[key] && !al->arg[key+1]) key++;
448     }
449     key = al->arg[key];
450     if (FLAG(i)) key = toupper(key);
451     al->next = TT.fixed[key];
452     TT.fixed[key] = al;
453   }
454 
455   // Sort each fast path pattern set by length so first hit is longest match
456   if (TT.e) for (key = 0; key<256; key++) {
457     if (!TT.fixed[key]) continue;
458     for (len = 0, al = TT.fixed[key]; al; al = al->next) len++;
459     last = xmalloc(len*sizeof(void *));
460     for (len = 0, al = TT.fixed[key]; al; al = al->next) last[len++] = al;
461     qsort(last, len, sizeof(void *), (void *)lensort);
462     for (ii = 0; ii<len; ii++) last[ii]->next = ii ? last[ii-1] : 0;
463     TT.fixed[key] = last[len-1];
464     free(last);
465   }
466 }
467 
do_grep_r(struct dirtree * new)468 static int do_grep_r(struct dirtree *new)
469 {
470   struct arg_list *al;
471   char *name;
472 
473   if (!new->parent) TT.tried++;
474   if (!dirtree_notdotdot(new)) return 0;
475   if (S_ISDIR(new->st.st_mode)) {
476     for (al = TT.exclude_dir; al; al = al->next)
477       if (!fnmatch(al->arg, new->name, 0)) return 0;
478     return DIRTREE_RECURSE|DIRTREE_SYMFOLLOW*FLAG(R);
479   }
480   if (TT.S || TT.M) {
481     for (al = TT.S; al; al = al->next)
482       if (!fnmatch(al->arg, new->name, 0)) return 0;
483 
484     if (TT.M) {
485       for (al = TT.M; al; al = al->next)
486         if (!fnmatch(al->arg, new->name, 0)) break;
487 
488       if (!al) return 0;
489     }
490   }
491 
492   // "grep -r onefile" doesn't show filenames, but "grep -r onedir" should.
493   if (new->parent && !FLAG(h)) toys.optflags |= FLAG_H;
494 
495   name = dirtree_path(new, 0);
496   do_grep(openat(dirtree_parentfd(new), new->name, 0), name);
497   free(name);
498 
499   return 0;
500 }
501 
grep_main(void)502 void grep_main(void)
503 {
504   char **ss = toys.optargs;
505 
506   if (FLAG(color) && (!TT.color || !strcmp(TT.color, "auto")) && !isatty(1))
507     toys.optflags &= ~FLAG_color;
508 
509   if (FLAG(color)) {
510     TT.purple = "\e[35m";
511     TT.cyan = "\e[36m";
512     TT.red = "\e[1;31m";
513     TT.green = "\e[32m";
514     TT.grey = "\e[m";
515   } else TT.purple = TT.cyan = TT.red = TT.green = TT.grey = "";
516 
517   if (FLAG(R)) toys.optflags |= FLAG_r;
518 
519   // Grep exits with 2 for errors
520   toys.exitval = 2;
521 
522   if (!TT.A) TT.A = TT.C;
523   if (!TT.B) TT.B = TT.C;
524 
525   TT.delim = '\n' * !FLAG(z);
526 
527   // Handle egrep and fgrep
528   if (*toys.which->name == 'e') toys.optflags |= FLAG_E;
529   if (*toys.which->name == 'f') toys.optflags |= FLAG_F;
530 
531   if (!TT.e && !TT.f) {
532     if (!*ss) error_exit("no REGEX");
533     TT.e = xzalloc(sizeof(struct arg_list));
534     TT.e->arg = *(ss++);
535     toys.optc--;
536   }
537 
538   parse_regex();
539 
540   if (!FLAG(h) && toys.optc>1) toys.optflags |= FLAG_H;
541 
542   if (FLAG(s)) {
543     close(2);
544     xopen_stdio("/dev/null", O_RDWR);
545   }
546 
547   if (FLAG(r)) {
548     // Iterate through -r arguments. Use "." as default if none provided.
549     for (ss = *ss ? ss : (char *[]){".", 0}; *ss; ss++) {
550       if (!strcmp(*ss, "-")) do_grep(0, *ss);
551       else dirtree_read(*ss, do_grep_r);
552     }
553   } else loopfiles_rw(ss, O_RDONLY|WARN_ONLY, 0, do_grep);
554   if (TT.tried >= toys.optc || (FLAG(q)&&TT.found)) toys.exitval = !TT.found;
555 }
556