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