• 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 
85 #ifdef TOYBOX_OH_ADAPT
86 struct line_info {
87   char *line;
88   unsigned start;
89   unsigned size;
90 };
91 #endif
92 
numdash(long num,char dash)93 static void numdash(long num, char dash)
94 {
95   printf("%s%ld%s%c", TT.green, num, TT.cyan, dash);
96 }
97 
98 // Emit line with various potential prefixes and delimiter
outline(char * line,char dash,char * name,long lcount,long bcount,unsigned trim)99 static void outline(char *line, char dash, char *name, long lcount, long bcount,
100   unsigned trim)
101 {
102   if (!trim && FLAG(o)) return;
103   if (name && FLAG(H)) printf("%s%s%s%c", TT.purple, name, TT.cyan, dash);
104   if (FLAG(c)) xprintf("%s%ld%c", TT.grey, lcount, TT.delim);
105   else if (lcount && FLAG(n)) numdash(lcount, dash);
106   if (bcount && FLAG(b)) numdash(bcount-1, dash);
107   if (line) {
108     if (FLAG(color)) xputsn(FLAG(o) ? TT.red : TT.grey);
109     // support embedded NUL bytes in output
110     xputsl(line, trim);
111     xputc(TT.delim);
112   }
113 }
114 
115 // Show matches in one file
do_grep(int fd,char * name)116 static void do_grep(int fd, char *name)
117 {
118   long lcount = 0, mcount = 0, offset = 0, after = 0, before = 0, new = 1;
119   struct double_list *dlb = 0;
120   char *bars = 0;
121   FILE *file;
122   int bin = 0;
123 
124   if (!FLAG(r)) TT.tried++;
125   if (!fd) name = "(standard input)";
126 
127   // Only run binary file check on lseekable files.
128   if (!FLAG(a) && !lseek(fd, 0, SEEK_CUR)) {
129     char buf[256];
130     int len, i = 0;
131     unsigned wc;
132 
133     // If the first 256 bytes don't parse as utf8, call it binary.
134     if (0<(len = read(fd, buf, 256))) {
135       lseek(fd, -len, SEEK_CUR);
136       while (i<len) {
137         bin = utf8towc(&wc, buf+i, len-i);
138         if (bin == -2) i = len;
139         if (bin<1) break;
140         i += bin;
141       }
142       bin = i!=len;
143     }
144     if (bin && FLAG(I)) return;
145   }
146 
147   if (!(file = fdopen(fd, "r"))) return perror_msg("%s", name);
148 
149   // Loop through lines of input
150   for (;;) {
151     char *line = 0, *start, *ss, *pp;
152     struct reg *shoe;
153     size_t ulen;
154     long len;
155     int matched = 0, rc = 1, move = 0, ii;
156 
157     // get next line, check and trim delimiter
158     lcount++;
159     errno = 0;
160     ulen = len = getdelim(&line, &ulen, TT.delim, file);
161     if (len == -1 && errno) perror_msg("%s", name);
162     if (len<1) break;
163     if (line[ulen-1] == TT.delim) line[--ulen] = 0;
164 
165     // Prepare for next line
166     start = line;
167     for (shoe = (void *)TT.reg; shoe; shoe = shoe->next) shoe->rc = 0;
168 
169     // Loop to handle multiple matches in same line
170     if (new) do {
171       regmatch_t *mm = (void *)toybuf;
172       struct arg_list *seek;
173 
174       mm->rm_so = mm->rm_eo = 0;
175       rc = 1;
176 
177       // Handle "fixed" (literal) matches (if any)
178       if (TT.e && *start) for (ss = start; ss-line<ulen; ss++) {
179         ii = FLAG(i) ? toupper(*ss) : *ss;
180         for (seek = TT.fixed[ii]; seek; seek = seek->next) {
181           if (*(pp = seek->arg)=='^' && !FLAG(F)) {
182             if (ss!=start) continue;
183             pp++;
184           }
185           for (ii = 0; pp[ii] && ss[ii]; ii++) {
186             if (!FLAG(F)) {
187               if (pp[ii]=='.') continue;
188               if (pp[ii]=='\\' && pp[ii+1]) pp++;
189               else if (pp[ii]=='$' && !pp[ii+1]) break;
190             }
191             if (FLAG(i)) {
192               if (toupper(pp[ii])!=toupper(ss[ii])) break;
193             } else if (pp[ii]!=ss[ii]) break;
194           }
195           if (pp[ii] && (pp[ii]!='$' || pp[ii+1] || ss[ii])) continue;
196           mm->rm_eo = (mm->rm_so = ss-start)+ii;
197           rc = 0;
198 
199           goto got;
200         }
201         if (FLAG(x)) break;
202       }
203 
204       // Empty pattern always matches
205       if (rc && *TT.fixed && !FLAG(o)) rc = 0;
206 got:
207       // Handle regex matches (if any)
208       for (shoe = (void *)TT.reg; shoe; shoe = shoe->next) {
209         // Do we need to re-check this regex?
210         if (!shoe->rc) {
211           shoe->m.rm_so -= move;
212           shoe->m.rm_eo -= move;
213           if (!matched || shoe->m.rm_so<0)
214             shoe->rc = regexec0(&shoe->r, start, ulen-(start-line), 1,
215                                 &shoe->m, start==line ? 0 : REG_NOTBOL);
216         }
217 
218         // If we got a match, is it a _better_ match?
219         if (!shoe->rc && (rc || shoe->m.rm_so < mm->rm_so ||
220             (shoe->m.rm_so == mm->rm_so && shoe->m.rm_eo >= mm->rm_eo)))
221         {
222           mm = &shoe->m;
223           rc = 0;
224         }
225       }
226 
227       if (!rc && FLAG(o) && !mm->rm_eo && ulen>start-line) {
228         move = 1;
229         continue;
230       }
231 
232       if (!rc && FLAG(x) && (mm->rm_so || ulen-(start-line)!=mm->rm_eo)) rc = 1;
233 
234       if (!rc && FLAG(w)) {
235         char c = 0;
236 
237         if ((start+mm->rm_so)!=line) {
238           c = start[mm->rm_so-1];
239           if (!isalnum(c) && c != '_') c = 0;
240         }
241         if (!c) {
242           c = start[mm->rm_eo];
243           if (!isalnum(c) && c != '_') c = 0;
244         }
245         if (c) {
246           move = mm->rm_so+1;
247           continue;
248         }
249       }
250 
251       if (FLAG(v)) {
252         if (FLAG(o)) {
253           if (rc) mm->rm_eo = ulen-(start-line);
254           else if (!mm->rm_so) {
255             move = mm->rm_eo;
256             continue;
257           } else mm->rm_eo = mm->rm_so;
258         } else {
259           if (!rc) break;
260           mm->rm_eo = ulen-(start-line);
261         }
262         mm->rm_so = 0;
263       } else if (rc) break;
264 
265       // At least one line we didn't print since match while -ABC active
266       if (bars) {
267         xputs(bars);
268         bars = 0;
269       }
270       matched++;
271       TT.found = 1;
272 
273       // Are we NOT showing the matching text?
274       if (FLAG(q)) {
275         toys.exitval = 0;
276         xexit();
277       }
278       if (FLAG(L) || FLAG(l)) {
279         if (FLAG(l)) xprintf("%s%c", name, '\n'*!FLAG(Z));
280         free(line);
281         fclose(file);
282         return;
283       }
284 
285       if (!FLAG(c)) {
286         long bcount = 1 + offset + (start-line) + (FLAG(o) ? mm->rm_so : 0);
287 
288         if (bin) printf("Binary file %s matches\n", name);
289         else if (FLAG(o))
290           outline(start+mm->rm_so, ':', name, lcount, bcount,
291                   mm->rm_eo-mm->rm_so);
292         else {
293           while (dlb) {
294             struct double_list *dl = dlist_pop(&dlb);
295 #ifdef TOYBOX_OH_ADAPT
296             struct line_info *linfo = (struct line_info *)dl->data;
297             outline(linfo->line, '-', name, lcount-before, linfo->start+1, linfo->size);
298             free(linfo->line);
299 #else
300             unsigned *uu = (void *)(dl->data+(strlen(dl->data)|3)+1);
301 
302             outline(dl->data, '-', name, lcount-before, uu[0]+1, uu[1]);
303 #endif
304             free(dl->data);
305             free(dl);
306             before--;
307           }
308 
309           if (matched==1)
310             outline(FLAG(color) ? 0 : line, ':', name, lcount, bcount, ulen);
311           if (FLAG(color)) {
312             xputsn(TT.grey);
313             if (mm->rm_so) xputsl(start, mm->rm_so);
314             xputsn(TT.red);
315             xputsl(start+mm->rm_so, mm->rm_eo-mm->rm_so);
316           }
317 
318           if (TT.A) after = TT.A+1;
319         }
320       }
321 
322       if (mm->rm_so == (move = mm->rm_eo)) break;
323     } while (*(start += move));
324     offset += len;
325 
326     if (matched) {
327       // Finish off pending line color fragment.
328       if (FLAG(color) && !FLAG(o)) {
329         xputsn(TT.grey);
330         if (ulen > start-line) xputsl(start, ulen-(start-line));
331         xputc(TT.delim);
332       }
333       mcount++;
334     } else {
335       int discard = (after || TT.B);
336 
337       if (after && --after) {
338         outline(line, '-', name, lcount, 0, ulen);
339         discard = 0;
340       }
341       if (discard && TT.B) {
342 #ifdef TOYBOX_OH_ADAPT
343         struct line_info *linfo = xzalloc(sizeof(struct line_info));
344         linfo->line = line;
345         linfo->start = offset - len;
346         linfo->size = ulen;
347         dlist_add(&dlb, linfo);
348 #else
349         unsigned *uu, ul = (ulen|3)+1;
350 
351         line = xrealloc(line, ul+8);
352         uu = (void *)(line+ul);
353         uu[0] = offset-len;
354         uu[1] = ulen;
355         dlist_add(&dlb, line);
356 #endif
357         line = 0;
358         if (++before>TT.B) {
359           struct double_list *dl;
360 
361           dl = dlist_pop(&dlb);
362 #ifdef TOYBOX_OH_ADAPT
363           struct line_info *linfo;
364           linfo = dl->data;
365           free(linfo->line);
366 #endif
367           free(dl->data);
368           free(dl);
369           before--;
370         } else discard = 0;
371       }
372       // If we discarded a line while displaying context, show bars before next
373       // line (but don't show them now in case that was last match in file)
374       if (discard && mcount) bars = "--";
375     }
376     free(line);
377 
378     if (FLAG(m) && mcount >= TT.m) {
379       if (!after) break;
380       new = 0;
381     }
382   }
383 
384   if (FLAG(L)) xprintf("%s%c", name, TT.delim);
385   else if (FLAG(c)) outline(0, ':', name, mcount, 0, 1);
386 
387   // loopfiles will also close the fd, but this frees an (opaque) struct.
388   fclose(file);
389   llist_traverse(dlb, llist_free_double);
390 }
391 
lensort(struct arg_list ** a,struct arg_list ** b)392 static int lensort(struct arg_list **a, struct arg_list **b)
393 {
394   long la = strlen((*a)->arg), lb = strlen((*b)->arg);
395 
396   if (la<lb) return -1;
397   if (la>lb) return 1;
398 
399   return 0;
400 }
401 
parse_regex(void)402 static void parse_regex(void)
403 {
404   struct arg_list *al, *new, *list = NULL, **last;
405   char *s, *ss, *special = "\\.^$[()|*+?{";
406   int len, ii, key;
407 
408   // Add all -f lines to -e list. (Yes, this is leaking allocation context for
409   // exit to free. Not supporting nofork for this command any time soon.)
410   al = TT.f ? TT.f : TT.e;
411   while (al) {
412     if (TT.f) {
413       if (!*(s = xreadfile(al->arg, 0, 0))) {
414         free(s);
415         s = 0;
416       } else if (*(ss = s+strlen(s)-1)=='\n') *ss = 0;
417     } else s = al->arg;
418 
419     // Advance, when we run out of -f switch to -e.
420     al = al->next;
421     if (!al && TT.f) {
422       TT.f = 0;
423       al = TT.e;
424     }
425     if (!s) continue;
426 
427     // NOTE: even with -z, -f is still \n delimited. Blank line = match all
428     // Split lines at \n, add individual lines to new list.
429     do {
430       if ((ss = strchr(s, '\n'))) *(ss++) = 0;
431       new = xmalloc(sizeof(struct arg_list));
432       new->next = list;
433       new->arg = s;
434       list = new;
435       s = ss;
436     } while (s);
437   }
438   TT.e = list;
439 
440   // Convert to regex where appropriate
441   for (last = &TT.e; *last;) {
442     // Can we use the fast path?
443     s = (*last)->arg;
444     if ('.'!=*s && !FLAG(F) && strcmp(s, "^$")) for (; *s; s++) {
445       if (*s=='\\') {
446         if (!s[1] || !strchr(special, *++s)) break;
447         if (!FLAG(E) && *s=='(') break;
448       } else if (*s>127 || strchr(special+4, *s)) break;
449     }
450 
451     // Add entry to fast path (literal-ish match) or slow path (regexec)
452     if (!*s || FLAG(F)) last = &((*last)->next);
453     else {
454       struct reg *shoe;
455 
456       dlist_add_nomalloc(&TT.reg, (void *)(shoe = xmalloc(sizeof(struct reg))));
457       xregcomp(&shoe->r, (*last)->arg, REG_EXTENDED*FLAG(E)|REG_ICASE*FLAG(i));
458       al = *last;
459       *last = (*last)->next;
460       free(al);
461     }
462   }
463   dlist_terminate(TT.reg);
464 
465   // Sort fast path patterns into buckets by first character
466   for (al = TT.e; al; al = new) {
467     new = al->next;
468     if (FLAG(F)) key = 0;
469     else {
470       key = '^'==*al->arg;
471       if ('\\'==al->arg[key]) key++;
472       else if ('$'==al->arg[key] && !al->arg[key+1]) key++;
473     }
474     key = al->arg[key];
475     if (FLAG(i)) key = toupper(key);
476     al->next = TT.fixed[key];
477     TT.fixed[key] = al;
478   }
479 
480   // Sort each fast path pattern set by length so first hit is longest match
481   if (TT.e) for (key = 0; key<256; key++) {
482     if (!TT.fixed[key]) continue;
483     for (len = 0, al = TT.fixed[key]; al; al = al->next) len++;
484     last = xmalloc(len*sizeof(void *));
485     for (len = 0, al = TT.fixed[key]; al; al = al->next) last[len++] = al;
486     qsort(last, len, sizeof(void *), (void *)lensort);
487     for (ii = 0; ii<len; ii++) last[ii]->next = ii ? last[ii-1] : 0;
488     TT.fixed[key] = last[len-1];
489     free(last);
490   }
491 }
492 
do_grep_r(struct dirtree * new)493 static int do_grep_r(struct dirtree *new)
494 {
495   struct arg_list *al;
496   char *name;
497 
498   if (!new->parent) TT.tried++;
499   if (!dirtree_notdotdot(new)) return 0;
500   if (S_ISDIR(new->st.st_mode)) {
501     for (al = TT.exclude_dir; al; al = al->next)
502       if (!fnmatch(al->arg, new->name, 0)) return 0;
503     return DIRTREE_RECURSE|DIRTREE_SYMFOLLOW*FLAG(R);
504   }
505   if (TT.S || TT.M) {
506     for (al = TT.S; al; al = al->next)
507       if (!fnmatch(al->arg, new->name, 0)) return 0;
508 
509     if (TT.M) {
510       for (al = TT.M; al; al = al->next)
511         if (!fnmatch(al->arg, new->name, 0)) break;
512 
513       if (!al) return 0;
514     }
515   }
516 
517   // "grep -r onefile" doesn't show filenames, but "grep -r onedir" should.
518   if (new->parent && !FLAG(h)) toys.optflags |= FLAG_H;
519 
520   name = dirtree_path(new, 0);
521   do_grep(openat(dirtree_parentfd(new), new->name, 0), name);
522   free(name);
523 
524   return 0;
525 }
526 
grep_main(void)527 void grep_main(void)
528 {
529   char **ss = toys.optargs;
530 
531   if (FLAG(color) && (!TT.color || !strcmp(TT.color, "auto")) && !isatty(1))
532     toys.optflags &= ~FLAG_color;
533 
534   if (FLAG(color)) {
535     TT.purple = "\e[35m";
536     TT.cyan = "\e[36m";
537     TT.red = "\e[1;31m";
538     TT.green = "\e[32m";
539     TT.grey = "\e[m";
540   } else TT.purple = TT.cyan = TT.red = TT.green = TT.grey = "";
541 
542   if (FLAG(R)) toys.optflags |= FLAG_r;
543 
544   // Grep exits with 2 for errors
545   toys.exitval = 2;
546 
547   if (!TT.A) TT.A = TT.C;
548   if (!TT.B) TT.B = TT.C;
549 
550   TT.delim = '\n' * !FLAG(z);
551 
552   // Handle egrep and fgrep
553   if (*toys.which->name == 'e') toys.optflags |= FLAG_E;
554   if (*toys.which->name == 'f') toys.optflags |= FLAG_F;
555 
556   if (!TT.e && !TT.f) {
557     if (!*ss) error_exit("no REGEX");
558     TT.e = xzalloc(sizeof(struct arg_list));
559     TT.e->arg = *(ss++);
560     toys.optc--;
561   }
562 
563   parse_regex();
564 
565   if (!FLAG(h) && toys.optc>1) toys.optflags |= FLAG_H;
566 
567   if (FLAG(s)) {
568     close(2);
569     xopen_stdio("/dev/null", O_RDWR);
570   }
571 
572   if (FLAG(r)) {
573     // Iterate through -r arguments. Use "." as default if none provided.
574     for (ss = *ss ? ss : (char *[]){".", 0}; *ss; ss++) {
575       if (!strcmp(*ss, "-")) do_grep(0, *ss);
576       else dirtree_read(*ss, do_grep_r);
577     }
578   } else loopfiles_rw(ss, O_RDONLY|WARN_ONLY, 0, do_grep);
579   if (TT.tried >= toys.optc || (FLAG(q)&&TT.found)) toys.exitval = !TT.found;
580 }
581