]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - usr.bin/grep/util.c
grep: fix null pattern and empty pattern file behavior
[FreeBSD/FreeBSD.git] / usr.bin / grep / util.c
1 /*      $NetBSD: util.c,v 1.9 2011/02/27 17:33:37 joerg Exp $   */
2 /*      $FreeBSD$       */
3 /*      $OpenBSD: util.c,v 1.39 2010/07/02 22:18:03 tedu Exp $  */
4
5 /*-
6  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
7  *
8  * Copyright (c) 1999 James Howard and Dag-Erling Coïdan Smørgrav
9  * Copyright (C) 2008-2010 Gabor Kovesdan <gabor@FreeBSD.org>
10  * Copyright (C) 2017 Kyle Evans <kevans@FreeBSD.org>
11  * All rights reserved.
12  *
13  * Redistribution and use in source and binary forms, with or without
14  * modification, are permitted provided that the following conditions
15  * are met:
16  * 1. Redistributions of source code must retain the above copyright
17  *    notice, this list of conditions and the following disclaimer.
18  * 2. Redistributions in binary form must reproduce the above copyright
19  *    notice, this list of conditions and the following disclaimer in the
20  *    documentation and/or other materials provided with the distribution.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34
35 #include <sys/cdefs.h>
36 __FBSDID("$FreeBSD$");
37
38 #include <sys/stat.h>
39 #include <sys/types.h>
40
41 #include <ctype.h>
42 #include <err.h>
43 #include <errno.h>
44 #include <fnmatch.h>
45 #include <fts.h>
46 #include <libgen.h>
47 #include <stdbool.h>
48 #include <stdio.h>
49 #include <stdlib.h>
50 #include <string.h>
51 #include <unistd.h>
52 #include <wchar.h>
53 #include <wctype.h>
54
55 #include "grep.h"
56
57 static bool      first_match = true;
58
59 /*
60  * Match printing context
61  */
62 struct mprintc {
63         long long       tail;           /* Number of trailing lines to record */
64         int             last_outed;     /* Number of lines since last output */
65         bool            doctx;          /* Printing context? */
66         bool            printmatch;     /* Printing matches? */
67         bool            same_file;      /* Same file as previously printed? */
68 };
69
70 static void procmatch_match(struct mprintc *mc, struct parsec *pc);
71 static void procmatch_nomatch(struct mprintc *mc, struct parsec *pc);
72 static bool procmatches(struct mprintc *mc, struct parsec *pc, bool matched);
73 #ifdef WITH_INTERNAL_NOSPEC
74 static int litexec(const struct pat *pat, const char *string,
75     size_t nmatch, regmatch_t pmatch[]);
76 #endif
77 static bool procline(struct parsec *pc);
78 static void printline(struct parsec *pc, int sep);
79 static void printline_metadata(struct str *line, int sep);
80
81 bool
82 file_matching(const char *fname)
83 {
84         char *fname_base, *fname_buf;
85         bool ret;
86
87         ret = finclude ? false : true;
88         fname_buf = strdup(fname);
89         if (fname_buf == NULL)
90                 err(2, "strdup");
91         fname_base = basename(fname_buf);
92
93         for (unsigned int i = 0; i < fpatterns; ++i) {
94                 if (fnmatch(fpattern[i].pat, fname, 0) == 0 ||
95                     fnmatch(fpattern[i].pat, fname_base, 0) == 0)
96                         /*
97                          * The last pattern matched wins exclusion/inclusion
98                          * rights, so we can't reasonably bail out early here.
99                          */
100                         ret = (fpattern[i].mode != EXCL_PAT);
101         }
102         free(fname_buf);
103         return (ret);
104 }
105
106 static inline bool
107 dir_matching(const char *dname)
108 {
109         bool ret;
110
111         ret = dinclude ? false : true;
112
113         for (unsigned int i = 0; i < dpatterns; ++i) {
114                 if (dname != NULL && fnmatch(dpattern[i].pat, dname, 0) == 0)
115                         /*
116                          * The last pattern matched wins exclusion/inclusion
117                          * rights, so we can't reasonably bail out early here.
118                          */
119                         ret = (dpattern[i].mode != EXCL_PAT);
120         }
121         return (ret);
122 }
123
124 /*
125  * Processes a directory when a recursive search is performed with
126  * the -R option.  Each appropriate file is passed to procfile().
127  */
128 bool
129 grep_tree(char **argv)
130 {
131         FTS *fts;
132         FTSENT *p;
133         int fts_flags;
134         bool matched, ok;
135         const char *wd[] = { ".", NULL };
136
137         matched = false;
138
139         /* This switch effectively initializes 'fts_flags' */
140         switch(linkbehave) {
141         case LINK_EXPLICIT:
142                 fts_flags = FTS_COMFOLLOW;
143                 break;
144         case LINK_SKIP:
145                 fts_flags = FTS_PHYSICAL;
146                 break;
147         default:
148                 fts_flags = FTS_LOGICAL;
149         }
150
151         fts_flags |= FTS_NOSTAT | FTS_NOCHDIR;
152
153         fts = fts_open((argv[0] == NULL) ?
154             __DECONST(char * const *, wd) : argv, fts_flags, NULL);
155         if (fts == NULL)
156                 err(2, "fts_open");
157         while (errno = 0, (p = fts_read(fts)) != NULL) {
158                 switch (p->fts_info) {
159                 case FTS_DNR:
160                         /* FALLTHROUGH */
161                 case FTS_ERR:
162                         file_err = true;
163                         if(!sflag)
164                                 warnx("%s: %s", p->fts_path, strerror(p->fts_errno));
165                         break;
166                 case FTS_D:
167                         /* FALLTHROUGH */
168                 case FTS_DP:
169                         if (dexclude || dinclude)
170                                 if (!dir_matching(p->fts_name) ||
171                                     !dir_matching(p->fts_path))
172                                         fts_set(fts, p, FTS_SKIP);
173                         break;
174                 case FTS_DC:
175                         /* Print a warning for recursive directory loop */
176                         warnx("warning: %s: recursive directory loop",
177                             p->fts_path);
178                         break;
179                 default:
180                         /* Check for file exclusion/inclusion */
181                         ok = true;
182                         if (fexclude || finclude)
183                                 ok &= file_matching(p->fts_path);
184
185                         if (ok && procfile(p->fts_path))
186                                 matched = true;
187                         break;
188                 }
189         }
190         if (errno != 0)
191                 err(2, "fts_read");
192
193         fts_close(fts);
194         return (matched);
195 }
196
197 static void
198 procmatch_match(struct mprintc *mc, struct parsec *pc)
199 {
200
201         if (mc->doctx) {
202                 if (!first_match && (!mc->same_file || mc->last_outed > 0))
203                         printf("--\n");
204                 if (Bflag > 0)
205                         printqueue();
206                 mc->tail = Aflag;
207         }
208
209         /* Print the matching line, but only if not quiet/binary */
210         if (mc->printmatch) {
211                 printline(pc, ':');
212                 while (pc->matchidx >= MAX_MATCHES) {
213                         /* Reset matchidx and try again */
214                         pc->matchidx = 0;
215                         if (procline(pc) == !vflag)
216                                 printline(pc, ':');
217                         else
218                                 break;
219                 }
220                 first_match = false;
221                 mc->same_file = true;
222                 mc->last_outed = 0;
223         }
224 }
225
226 static void
227 procmatch_nomatch(struct mprintc *mc, struct parsec *pc)
228 {
229
230         /* Deal with any -A context as needed */
231         if (mc->tail > 0) {
232                 grep_printline(&pc->ln, '-');
233                 mc->tail--;
234                 if (Bflag > 0)
235                         clearqueue();
236         } else if (Bflag == 0 || (Bflag > 0 && enqueue(&pc->ln)))
237                 /*
238                  * Enqueue non-matching lines for -B context. If we're not
239                  * actually doing -B context or if the enqueue resulted in a
240                  * line being rotated out, then go ahead and increment
241                  * last_outed to signify a gap between context/match.
242                  */
243                 ++mc->last_outed;
244 }
245
246 /*
247  * Process any matches in the current parsing context, return a boolean
248  * indicating whether we should halt any further processing or not. 'true' to
249  * continue processing, 'false' to halt.
250  */
251 static bool
252 procmatches(struct mprintc *mc, struct parsec *pc, bool matched)
253 {
254
255         /*
256          * XXX TODO: This should loop over pc->matches and handle things on a
257          * line-by-line basis, setting up a `struct str` as needed.
258          */
259         /* Deal with any -B context or context separators */
260         if (matched) {
261                 procmatch_match(mc, pc);
262
263                 /* Count the matches if we have a match limit */
264                 if (mflag) {
265                         /* XXX TODO: Decrement by number of matched lines */
266                         mcount -= 1;
267                         if (mcount <= 0)
268                                 return (false);
269                 }
270         } else if (mc->doctx)
271                 procmatch_nomatch(mc, pc);
272
273         return (true);
274 }
275
276 /*
277  * Opens a file and processes it.  Each file is processed line-by-line
278  * passing the lines to procline().
279  */
280 bool
281 procfile(const char *fn)
282 {
283         struct parsec pc;
284         struct mprintc mc;
285         struct file *f;
286         struct stat sb;
287         mode_t s;
288         int lines;
289         bool line_matched;
290
291         if (strcmp(fn, "-") == 0) {
292                 fn = label != NULL ? label : errstr[1];
293                 f = grep_open(NULL);
294         } else {
295                 if (stat(fn, &sb) == 0) {
296                         /* Check if we need to process the file */
297                         s = sb.st_mode & S_IFMT;
298                         if (dirbehave == DIR_SKIP && s == S_IFDIR)
299                                 return (false);
300                         if (devbehave == DEV_SKIP && (s == S_IFIFO ||
301                             s == S_IFCHR || s == S_IFBLK || s == S_IFSOCK))
302                                 return (false);
303                 }
304                 f = grep_open(fn);
305         }
306         if (f == NULL) {
307                 file_err = true;
308                 if (!sflag)
309                         warn("%s", fn);
310                 return (false);
311         }
312
313         pc.ln.file = grep_strdup(fn);
314         pc.ln.line_no = 0;
315         pc.ln.len = 0;
316         pc.ln.boff = 0;
317         pc.ln.off = -1;
318         pc.binary = f->binary;
319         pc.cntlines = false;
320         memset(&mc, 0, sizeof(mc));
321         mc.printmatch = true;
322         if ((pc.binary && binbehave == BINFILE_BIN) || cflag || qflag ||
323             lflag || Lflag)
324                 mc.printmatch = false;
325         if (mc.printmatch && (Aflag != 0 || Bflag != 0))
326                 mc.doctx = true;
327         if (mc.printmatch && (Aflag != 0 || Bflag != 0 || mflag || nflag))
328                 pc.cntlines = true;
329         mcount = mlimit;
330
331         for (lines = 0; lines == 0 || !(lflag || qflag); ) {
332                 /*
333                  * XXX TODO: We need to revisit this in a chunking world. We're
334                  * not going to be doing per-line statistics because of the
335                  * overhead involved. procmatches can figure that stuff out as
336                  * needed. */
337                 /* Reset per-line statistics */
338                 pc.printed = 0;
339                 pc.matchidx = 0;
340                 pc.lnstart = 0;
341                 pc.ln.boff = 0;
342                 pc.ln.off += pc.ln.len + 1;
343                 /* XXX TODO: Grab a chunk */
344                 if ((pc.ln.dat = grep_fgetln(f, &pc)) == NULL ||
345                     pc.ln.len == 0)
346                         break;
347
348                 if (pc.ln.len > 0 && pc.ln.dat[pc.ln.len - 1] == fileeol)
349                         --pc.ln.len;
350                 pc.ln.line_no++;
351
352                 /* Return if we need to skip a binary file */
353                 if (pc.binary && binbehave == BINFILE_SKIP) {
354                         grep_close(f);
355                         free(pc.ln.file);
356                         free(f);
357                         return (0);
358                 }
359
360                 line_matched = procline(&pc) == !vflag;
361                 if (line_matched)
362                         ++lines;
363
364                 /* Halt processing if we hit our match limit */
365                 if (!procmatches(&mc, &pc, line_matched))
366                         break;
367         }
368         if (Bflag > 0)
369                 clearqueue();
370         grep_close(f);
371
372         if (cflag) {
373                 if (!hflag)
374                         printf("%s:", pc.ln.file);
375                 printf("%u\n", lines);
376         }
377         if (lflag && !qflag && lines != 0)
378                 printf("%s%c", fn, nullflag ? 0 : '\n');
379         if (Lflag && !qflag && lines == 0)
380                 printf("%s%c", fn, nullflag ? 0 : '\n');
381         if (lines != 0 && !cflag && !lflag && !Lflag &&
382             binbehave == BINFILE_BIN && f->binary && !qflag)
383                 printf(errstr[7], fn);
384
385         free(pc.ln.file);
386         free(f);
387         return (lines != 0);
388 }
389
390 #ifdef WITH_INTERNAL_NOSPEC
391 /*
392  * Internal implementation of literal string search within a string, modeled
393  * after regexec(3), for use when the regex(3) implementation doesn't offer
394  * either REG_NOSPEC or REG_LITERAL. This does not apply in the default FreeBSD
395  * config, but in other scenarios such as building against libgnuregex or on
396  * some non-FreeBSD OSes.
397  */
398 static int
399 litexec(const struct pat *pat, const char *string, size_t nmatch,
400     regmatch_t pmatch[])
401 {
402         char *(*strstr_fn)(const char *, const char *);
403         char *sub, *subject;
404         const char *search;
405         size_t idx, n, ofs, stringlen;
406
407         if (cflags & REG_ICASE)
408                 strstr_fn = strcasestr;
409         else
410                 strstr_fn = strstr;
411         idx = 0;
412         ofs = pmatch[0].rm_so;
413         stringlen = pmatch[0].rm_eo;
414         if (ofs >= stringlen)
415                 return (REG_NOMATCH);
416         subject = strndup(string, stringlen);
417         if (subject == NULL)
418                 return (REG_ESPACE);
419         for (n = 0; ofs < stringlen;) {
420                 search = (subject + ofs);
421                 if ((unsigned long)pat->len > strlen(search))
422                         break;
423                 sub = strstr_fn(search, pat->pat);
424                 /*
425                  * Ignoring the empty string possibility due to context: grep optimizes
426                  * for empty patterns and will never reach this point.
427                  */
428                 if (sub == NULL)
429                         break;
430                 ++n;
431                 /* Fill in pmatch if necessary */
432                 if (nmatch > 0) {
433                         pmatch[idx].rm_so = ofs + (sub - search);
434                         pmatch[idx].rm_eo = pmatch[idx].rm_so + pat->len;
435                         if (++idx == nmatch)
436                                 break;
437                         ofs = pmatch[idx].rm_so + 1;
438                 } else
439                         /* We only needed to know if we match or not */
440                         break;
441         }
442         free(subject);
443         if (n > 0 && nmatch > 0)
444                 for (n = idx; n < nmatch; ++n)
445                         pmatch[n].rm_so = pmatch[n].rm_eo = -1;
446
447         return (n > 0 ? 0 : REG_NOMATCH);
448 }
449 #endif /* WITH_INTERNAL_NOSPEC */
450
451 #define iswword(x)      (iswalnum((x)) || (x) == L'_')
452
453 /*
454  * Processes a line comparing it with the specified patterns.  Each pattern
455  * is looped to be compared along with the full string, saving each and every
456  * match, which is necessary to colorize the output and to count the
457  * matches.  The matching lines are passed to printline() to display the
458  * appropriate output.
459  */
460 static bool
461 procline(struct parsec *pc)
462 {
463         regmatch_t pmatch, lastmatch, chkmatch;
464         wchar_t wbegin, wend;
465         size_t st, nst;
466         unsigned int i;
467         int r = 0, leflags = eflags;
468         size_t startm = 0, matchidx;
469         unsigned int retry;
470         bool lastmatched, matched;
471
472         matchidx = pc->matchidx;
473
474         /* Null pattern shortcuts. */
475         if (matchall) {
476                 if (xflag && pc->ln.len == 0) {
477                         /* Matches empty lines (-x). */
478                         return (true);
479                 } else if (!wflag && !xflag) {
480                         /* Matches every line (no -w or -x). */
481                         return (true);
482                 }
483
484                 /*
485                  * If we only have the NULL pattern, whether we match or not
486                  * depends on if we got here with -w or -x.  If either is set,
487                  * the answer is no.  If we have other patterns, we'll defer
488                  * to them.
489                  */
490                 if (patterns == 0) {
491                         return (!(wflag || xflag));
492                 }
493         } else if (patterns == 0) {
494                 /* Pattern file with no patterns. */
495                 return (false);
496         }
497
498         matched = false;
499         st = pc->lnstart;
500         nst = 0;
501         /* Initialize to avoid a false positive warning from GCC. */
502         lastmatch.rm_so = lastmatch.rm_eo = 0;
503
504         /* Loop to process the whole line */
505         while (st <= pc->ln.len) {
506                 lastmatched = false;
507                 startm = matchidx;
508                 retry = 0;
509                 if (st > 0 && pc->ln.dat[st - 1] != fileeol)
510                         leflags |= REG_NOTBOL;
511                 /* Loop to compare with all the patterns */
512                 for (i = 0; i < patterns; i++) {
513                         pmatch.rm_so = st;
514                         pmatch.rm_eo = pc->ln.len;
515 #ifdef WITH_INTERNAL_NOSPEC
516                         if (grepbehave == GREP_FIXED)
517                                 r = litexec(&pattern[i], pc->ln.dat, 1, &pmatch);
518                         else
519 #endif
520                         r = regexec(&r_pattern[i], pc->ln.dat, 1, &pmatch,
521                             leflags);
522                         if (r != 0)
523                                 continue;
524                         /* Check for full match */
525                         if (xflag && (pmatch.rm_so != 0 ||
526                             (size_t)pmatch.rm_eo != pc->ln.len))
527                                 continue;
528                         /* Check for whole word match */
529                         if (wflag) {
530                                 wbegin = wend = L' ';
531                                 if (pmatch.rm_so != 0 &&
532                                     sscanf(&pc->ln.dat[pmatch.rm_so - 1],
533                                     "%lc", &wbegin) != 1)
534                                         r = REG_NOMATCH;
535                                 else if ((size_t)pmatch.rm_eo !=
536                                     pc->ln.len &&
537                                     sscanf(&pc->ln.dat[pmatch.rm_eo],
538                                     "%lc", &wend) != 1)
539                                         r = REG_NOMATCH;
540                                 else if (iswword(wbegin) ||
541                                     iswword(wend))
542                                         r = REG_NOMATCH;
543                                 /*
544                                  * If we're doing whole word matching and we
545                                  * matched once, then we should try the pattern
546                                  * again after advancing just past the start of
547                                  * the earliest match. This allows the pattern
548                                  * to  match later on in the line and possibly
549                                  * still match a whole word.
550                                  */
551                                 if (r == REG_NOMATCH &&
552                                     (retry == pc->lnstart ||
553                                     (unsigned int)pmatch.rm_so + 1 < retry))
554                                         retry = pmatch.rm_so + 1;
555                                 if (r == REG_NOMATCH)
556                                         continue;
557                         }
558                         lastmatched = true;
559                         lastmatch = pmatch;
560
561                         if (matchidx == 0)
562                                 matched = true;
563
564                         /*
565                          * Replace previous match if the new one is earlier
566                          * and/or longer. This will lead to some amount of
567                          * extra work if -o/--color are specified, but it's
568                          * worth it from a correctness point of view.
569                          */
570                         if (matchidx > startm) {
571                                 chkmatch = pc->matches[matchidx - 1];
572                                 if (pmatch.rm_so < chkmatch.rm_so ||
573                                     (pmatch.rm_so == chkmatch.rm_so &&
574                                     (pmatch.rm_eo - pmatch.rm_so) >
575                                     (chkmatch.rm_eo - chkmatch.rm_so))) {
576                                         pc->matches[matchidx - 1] = pmatch;
577                                         nst = pmatch.rm_eo;
578                                 }
579                         } else {
580                                 /* Advance as normal if not */
581                                 pc->matches[matchidx++] = pmatch;
582                                 nst = pmatch.rm_eo;
583                         }
584                         /* avoid excessive matching - skip further patterns */
585                         if ((color == NULL && !oflag) || qflag || lflag ||
586                             matchidx >= MAX_MATCHES) {
587                                 pc->lnstart = nst;
588                                 lastmatched = false;
589                                 break;
590                         }
591                 }
592
593                 /*
594                  * Advance to just past the start of the earliest match, try
595                  * again just in case we still have a chance to match later in
596                  * the string.
597                  */
598                 if (!lastmatched && retry > pc->lnstart) {
599                         st = retry;
600                         continue;
601                 }
602
603                 /* XXX TODO: We will need to keep going, since we're chunky */
604                 /* One pass if we are not recording matches */
605                 if (!wflag && ((color == NULL && !oflag) || qflag || lflag || Lflag))
606                         break;
607
608                 /* If we didn't have any matches or REG_NOSUB set */
609                 if (!lastmatched || (cflags & REG_NOSUB))
610                         nst = pc->ln.len;
611
612                 if (!lastmatched)
613                         /* No matches */
614                         break;
615                 else if (st == nst && lastmatch.rm_so == lastmatch.rm_eo)
616                         /* Zero-length match -- advance one more so we don't get stuck */
617                         nst++;
618
619                 /* Advance st based on previous matches */
620                 st = nst;
621                 pc->lnstart = st;
622         }
623
624         /* Reflect the new matchidx in the context */
625         pc->matchidx = matchidx;
626         return matched;
627 }
628
629 /*
630  * Safe malloc() for internal use.
631  */
632 void *
633 grep_malloc(size_t size)
634 {
635         void *ptr;
636
637         if ((ptr = malloc(size)) == NULL)
638                 err(2, "malloc");
639         return (ptr);
640 }
641
642 /*
643  * Safe calloc() for internal use.
644  */
645 void *
646 grep_calloc(size_t nmemb, size_t size)
647 {
648         void *ptr;
649
650         if ((ptr = calloc(nmemb, size)) == NULL)
651                 err(2, "calloc");
652         return (ptr);
653 }
654
655 /*
656  * Safe realloc() for internal use.
657  */
658 void *
659 grep_realloc(void *ptr, size_t size)
660 {
661
662         if ((ptr = realloc(ptr, size)) == NULL)
663                 err(2, "realloc");
664         return (ptr);
665 }
666
667 /*
668  * Safe strdup() for internal use.
669  */
670 char *
671 grep_strdup(const char *str)
672 {
673         char *ret;
674
675         if ((ret = strdup(str)) == NULL)
676                 err(2, "strdup");
677         return (ret);
678 }
679
680 /*
681  * Print an entire line as-is, there are no inline matches to consider. This is
682  * used for printing context.
683  */
684 void grep_printline(struct str *line, int sep) {
685         printline_metadata(line, sep);
686         fwrite(line->dat, line->len, 1, stdout);
687         putchar(fileeol);
688 }
689
690 static void
691 printline_metadata(struct str *line, int sep)
692 {
693         bool printsep;
694
695         printsep = false;
696         if (!hflag) {
697                 if (!nullflag) {
698                         fputs(line->file, stdout);
699                         printsep = true;
700                 } else {
701                         printf("%s", line->file);
702                         putchar(0);
703                 }
704         }
705         if (nflag) {
706                 if (printsep)
707                         putchar(sep);
708                 printf("%d", line->line_no);
709                 printsep = true;
710         }
711         if (bflag) {
712                 if (printsep)
713                         putchar(sep);
714                 printf("%lld", (long long)(line->off + line->boff));
715                 printsep = true;
716         }
717         if (printsep)
718                 putchar(sep);
719 }
720
721 /*
722  * Prints a matching line according to the command line options.
723  */
724 static void
725 printline(struct parsec *pc, int sep)
726 {
727         size_t a = 0;
728         size_t i, matchidx;
729         regmatch_t match;
730
731         /* If matchall, everything matches but don't actually print for -o */
732         if (oflag && matchall)
733                 return;
734
735         matchidx = pc->matchidx;
736
737         /* --color and -o */
738         if ((oflag || color) && matchidx > 0) {
739                 /* Only print metadata once per line if --color */
740                 if (!oflag && pc->printed == 0)
741                         printline_metadata(&pc->ln, sep);
742                 for (i = 0; i < matchidx; i++) {
743                         match = pc->matches[i];
744                         /* Don't output zero length matches */
745                         if (match.rm_so == match.rm_eo)
746                                 continue;
747                         /*
748                          * Metadata is printed on a per-line basis, so every
749                          * match gets file metadata with the -o flag.
750                          */
751                         if (oflag) {
752                                 pc->ln.boff = match.rm_so;
753                                 printline_metadata(&pc->ln, sep);
754                         } else
755                                 fwrite(pc->ln.dat + a, match.rm_so - a, 1,
756                                     stdout);
757                         if (color)
758                                 fprintf(stdout, "\33[%sm\33[K", color);
759                         fwrite(pc->ln.dat + match.rm_so,
760                             match.rm_eo - match.rm_so, 1, stdout);
761                         if (color)
762                                 fprintf(stdout, "\33[m\33[K");
763                         a = match.rm_eo;
764                         if (oflag)
765                                 putchar('\n');
766                 }
767                 if (!oflag) {
768                         if (pc->ln.len - a > 0)
769                                 fwrite(pc->ln.dat + a, pc->ln.len - a, 1,
770                                     stdout);
771                         putchar('\n');
772                 }
773         } else
774                 grep_printline(&pc->ln, sep);
775         pc->printed++;
776 }