• 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, new = 1;
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     if (new) 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) {
352       if (!after) break;
353       new = 0;
354     }
355   }
356 
357   if (FLAG(L)) xprintf("%s%c", name, TT.delim);
358   else if (FLAG(c)) outline(0, ':', name, mcount, 0, 1);
359 
360   // loopfiles will also close the fd, but this frees an (opaque) struct.
361   fclose(file);
362   llist_traverse(dlb, llist_free_double);
363 }
364 
lensort(struct arg_list ** a,struct arg_list ** b)365 static int lensort(struct arg_list **a, struct arg_list **b)
366 {
367   long la = strlen((*a)->arg), lb = strlen((*b)->arg);
368 
369   if (la<lb) return -1;
370   if (la>lb) return 1;
371 
372   return 0;
373 }
374 
parse_regex(void)375 static void parse_regex(void)
376 {
377   struct arg_list *al, *new, *list = NULL, **last;
378   char *s, *ss, *special = "\\.^$[()|*+?{";
379   int len, ii, key;
380 
381   // Add all -f lines to -e list. (Yes, this is leaking allocation context for
382   // exit to free. Not supporting nofork for this command any time soon.)
383   al = TT.f ? TT.f : TT.e;
384   while (al) {
385     if (TT.f) {
386       if (!*(s = xreadfile(al->arg, 0, 0))) {
387         free(s);
388         s = 0;
389       } else if (*(ss = s+strlen(s)-1)=='\n') *ss = 0;
390     } else s = al->arg;
391 
392     // Advance, when we run out of -f switch to -e.
393     al = al->next;
394     if (!al && TT.f) {
395       TT.f = 0;
396       al = TT.e;
397     }
398     if (!s) continue;
399 
400     // NOTE: even with -z, -f is still \n delimited. Blank line = match all
401     // Split lines at \n, add individual lines to new list.
402     do {
403       if ((ss = strchr(s, '\n'))) *(ss++) = 0;
404       new = xmalloc(sizeof(struct arg_list));
405       new->next = list;
406       new->arg = s;
407       list = new;
408       s = ss;
409     } while (s);
410   }
411   TT.e = list;
412 
413   // Convert to regex where appropriate
414   for (last = &TT.e; *last;) {
415     // Can we use the fast path?
416     s = (*last)->arg;
417     if ('.'!=*s && !FLAG(F) && strcmp(s, "^$")) for (; *s; s++) {
418       if (*s=='\\') {
419         if (!s[1] || !strchr(special, *++s)) break;
420         if (!FLAG(E) && *s=='(') break;
421       } else if (*s>127 || strchr(special+4, *s)) break;
422     }
423 
424     // Add entry to fast path (literal-ish match) or slow path (regexec)
425     if (!*s || FLAG(F)) last = &((*last)->next);
426     else {
427       struct reg *shoe;
428 
429       dlist_add_nomalloc(&TT.reg, (void *)(shoe = xmalloc(sizeof(struct reg))));
430       xregcomp(&shoe->r, (*last)->arg, REG_EXTENDED*FLAG(E)|REG_ICASE*FLAG(i));
431       al = *last;
432       *last = (*last)->next;
433       free(al);
434     }
435   }
436   dlist_terminate(TT.reg);
437 
438   // Sort fast path patterns into buckets by first character
439   for (al = TT.e; al; al = new) {
440     new = al->next;
441     if (FLAG(F)) key = 0;
442     else {
443       key = '^'==*al->arg;
444       if ('\\'==al->arg[key]) key++;
445       else if ('$'==al->arg[key] && !al->arg[key+1]) key++;
446     }
447     key = al->arg[key];
448     if (FLAG(i)) key = toupper(key);
449     al->next = TT.fixed[key];
450     TT.fixed[key] = al;
451   }
452 
453   // Sort each fast path pattern set by length so first hit is longest match
454   if (TT.e) for (key = 0; key<256; key++) {
455     if (!TT.fixed[key]) continue;
456     for (len = 0, al = TT.fixed[key]; al; al = al->next) len++;
457     last = xmalloc(len*sizeof(void *));
458     for (len = 0, al = TT.fixed[key]; al; al = al->next) last[len++] = al;
459     qsort(last, len, sizeof(void *), (void *)lensort);
460     for (ii = 0; ii<len; ii++) last[ii]->next = ii ? last[ii-1] : 0;
461     TT.fixed[key] = last[len-1];
462     free(last);
463   }
464 }
465 
do_grep_r(struct dirtree * new)466 static int do_grep_r(struct dirtree *new)
467 {
468   struct arg_list *al;
469   char *name;
470 
471   if (!new->parent) TT.tried++;
472   if (!dirtree_notdotdot(new)) return 0;
473   if (S_ISDIR(new->st.st_mode)) {
474     for (al = TT.exclude_dir; al; al = al->next)
475       if (!fnmatch(al->arg, new->name, 0)) return 0;
476     return DIRTREE_RECURSE|DIRTREE_SYMFOLLOW*FLAG(R);
477   }
478   if (TT.S || TT.M) {
479     for (al = TT.S; al; al = al->next)
480       if (!fnmatch(al->arg, new->name, 0)) return 0;
481 
482     if (TT.M) {
483       for (al = TT.M; al; al = al->next)
484         if (!fnmatch(al->arg, new->name, 0)) break;
485 
486       if (!al) return 0;
487     }
488   }
489 
490   // "grep -r onefile" doesn't show filenames, but "grep -r onedir" should.
491   if (new->parent && !FLAG(h)) toys.optflags |= FLAG_H;
492 
493   name = dirtree_path(new, 0);
494   do_grep(openat(dirtree_parentfd(new), new->name, 0), name);
495   free(name);
496 
497   return 0;
498 }
499 
grep_main(void)500 void grep_main(void)
501 {
502   char **ss = toys.optargs;
503 
504   if (FLAG(color) && (!TT.color || !strcmp(TT.color, "auto")) && !isatty(1))
505     toys.optflags &= ~FLAG_color;
506 
507   if (FLAG(color)) {
508     TT.purple = "\e[35m";
509     TT.cyan = "\e[36m";
510     TT.red = "\e[1;31m";
511     TT.green = "\e[32m";
512     TT.grey = "\e[m";
513   } else TT.purple = TT.cyan = TT.red = TT.green = TT.grey = "";
514 
515   if (FLAG(R)) toys.optflags |= FLAG_r;
516 
517   // Grep exits with 2 for errors
518   toys.exitval = 2;
519 
520   if (!TT.A) TT.A = TT.C;
521   if (!TT.B) TT.B = TT.C;
522 
523   TT.delim = '\n' * !FLAG(z);
524 
525   // Handle egrep and fgrep
526   if (*toys.which->name == 'e') toys.optflags |= FLAG_E;
527   if (*toys.which->name == 'f') toys.optflags |= FLAG_F;
528 
529   if (!TT.e && !TT.f) {
530     if (!*ss) error_exit("no REGEX");
531     TT.e = xzalloc(sizeof(struct arg_list));
532     TT.e->arg = *(ss++);
533     toys.optc--;
534   }
535 
536   parse_regex();
537 
538   if (!FLAG(h) && toys.optc>1) toys.optflags |= FLAG_H;
539 
540   if (FLAG(s)) {
541     close(2);
542     xopen_stdio("/dev/null", O_RDWR);
543   }
544 
545   if (FLAG(r)) {
546     // Iterate through -r arguments. Use "." as default if none provided.
547     for (ss = *ss ? ss : (char *[]){".", 0}; *ss; ss++) {
548       if (!strcmp(*ss, "-")) do_grep(0, *ss);
549       else dirtree_read(*ss, do_grep_r);
550     }
551   } else loopfiles_rw(ss, O_RDONLY|WARN_ONLY, 0, do_grep);
552   if (TT.tried >= toys.optc || (FLAG(q)&&TT.found)) toys.exitval = !TT.found;
553 }
554