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