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