xref: /freebsd/usr.bin/grep/util.c (revision 4c9ffb13dd74159bd3ed7e1c4c706dbd15a70df2)
1b66a823bSGabor Kovesdan /*	$NetBSD: util.c,v 1.9 2011/02/27 17:33:37 joerg Exp $	*/
24dc88ebeSGabor Kovesdan /*	$OpenBSD: util.c,v 1.39 2010/07/02 22:18:03 tedu Exp $	*/
34dc88ebeSGabor Kovesdan 
44dc88ebeSGabor Kovesdan /*-
54d846d26SWarner Losh  * SPDX-License-Identifier: BSD-2-Clause
61de7b4b8SPedro F. Giffuni  *
7e738085bSDag-Erling Smørgrav  * Copyright (c) 1999 James Howard and Dag-Erling Smørgrav
84dc88ebeSGabor Kovesdan  * Copyright (C) 2008-2010 Gabor Kovesdan <gabor@FreeBSD.org>
926e1c38fSKyle Evans  * Copyright (C) 2017 Kyle Evans <kevans@FreeBSD.org>
104dc88ebeSGabor Kovesdan  * All rights reserved.
114dc88ebeSGabor Kovesdan  *
124dc88ebeSGabor Kovesdan  * Redistribution and use in source and binary forms, with or without
134dc88ebeSGabor Kovesdan  * modification, are permitted provided that the following conditions
144dc88ebeSGabor Kovesdan  * are met:
154dc88ebeSGabor Kovesdan  * 1. Redistributions of source code must retain the above copyright
164dc88ebeSGabor Kovesdan  *    notice, this list of conditions and the following disclaimer.
174dc88ebeSGabor Kovesdan  * 2. Redistributions in binary form must reproduce the above copyright
184dc88ebeSGabor Kovesdan  *    notice, this list of conditions and the following disclaimer in the
194dc88ebeSGabor Kovesdan  *    documentation and/or other materials provided with the distribution.
204dc88ebeSGabor Kovesdan  *
214dc88ebeSGabor Kovesdan  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
224dc88ebeSGabor Kovesdan  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
234dc88ebeSGabor Kovesdan  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
244dc88ebeSGabor Kovesdan  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
254dc88ebeSGabor Kovesdan  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
264dc88ebeSGabor Kovesdan  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
274dc88ebeSGabor Kovesdan  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
284dc88ebeSGabor Kovesdan  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
294dc88ebeSGabor Kovesdan  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
304dc88ebeSGabor Kovesdan  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
314dc88ebeSGabor Kovesdan  * SUCH DAMAGE.
324dc88ebeSGabor Kovesdan  */
334dc88ebeSGabor Kovesdan 
344dc88ebeSGabor Kovesdan #include <sys/cdefs.h>
354dc88ebeSGabor Kovesdan #include <sys/stat.h>
364dc88ebeSGabor Kovesdan #include <sys/types.h>
374dc88ebeSGabor Kovesdan 
384dc88ebeSGabor Kovesdan #include <ctype.h>
394dc88ebeSGabor Kovesdan #include <err.h>
404dc88ebeSGabor Kovesdan #include <errno.h>
414dc88ebeSGabor Kovesdan #include <fnmatch.h>
424dc88ebeSGabor Kovesdan #include <fts.h>
434dc88ebeSGabor Kovesdan #include <libgen.h>
4455e44f51SGabor Kovesdan #include <stdbool.h>
454dc88ebeSGabor Kovesdan #include <stdio.h>
464dc88ebeSGabor Kovesdan #include <stdlib.h>
474dc88ebeSGabor Kovesdan #include <string.h>
484dc88ebeSGabor Kovesdan #include <unistd.h>
494dc88ebeSGabor Kovesdan #include <wchar.h>
504dc88ebeSGabor Kovesdan #include <wctype.h>
514dc88ebeSGabor Kovesdan 
524dc88ebeSGabor Kovesdan #include "grep.h"
534dc88ebeSGabor Kovesdan 
54a4f3f02bSEd Maste static bool	 first_match = true;
554dc88ebeSGabor Kovesdan 
56a4f3f02bSEd Maste /*
5781c634e8SKyle Evans  * Match printing context
5881c634e8SKyle Evans  */
5981c634e8SKyle Evans struct mprintc {
6081c634e8SKyle Evans 	long long	tail;		/* Number of trailing lines to record */
6181c634e8SKyle Evans 	int		last_outed;	/* Number of lines since last output */
6281c634e8SKyle Evans 	bool		doctx;		/* Printing context? */
6381c634e8SKyle Evans 	bool		printmatch;	/* Printing matches? */
6481c634e8SKyle Evans 	bool		same_file;	/* Same file as previously printed? */
6581c634e8SKyle Evans };
6681c634e8SKyle Evans 
67042db8e8SKyle Evans static void procmatch_match(struct mprintc *mc, struct parsec *pc);
68042db8e8SKyle Evans static void procmatch_nomatch(struct mprintc *mc, struct parsec *pc);
6981c634e8SKyle Evans static bool procmatches(struct mprintc *mc, struct parsec *pc, bool matched);
7005ad8215SKyle Evans #ifdef WITH_INTERNAL_NOSPEC
7105ad8215SKyle Evans static int litexec(const struct pat *pat, const char *string,
7205ad8215SKyle Evans     size_t nmatch, regmatch_t pmatch[]);
7305ad8215SKyle Evans #endif
74be13c0f9SKyle Evans static bool procline(struct parsec *pc);
75*4c9ffb13SKyle Evans static bool printline(struct parsec *pc, int sep, size_t *last_out);
76a4f3f02bSEd Maste static void printline_metadata(struct str *line, int sep);
7722130a21SEd Maste 
7855e44f51SGabor Kovesdan bool
file_matching(const char * fname)7955e44f51SGabor Kovesdan file_matching(const char *fname)
8055e44f51SGabor Kovesdan {
8133f5799aSEd Schouten 	char *fname_base, *fname_buf;
8255e44f51SGabor Kovesdan 	bool ret;
8355e44f51SGabor Kovesdan 
8455e44f51SGabor Kovesdan 	ret = finclude ? false : true;
8533f5799aSEd Schouten 	fname_buf = strdup(fname);
8633f5799aSEd Schouten 	if (fname_buf == NULL)
8733f5799aSEd Schouten 		err(2, "strdup");
8833f5799aSEd Schouten 	fname_base = basename(fname_buf);
8955e44f51SGabor Kovesdan 
9055e44f51SGabor Kovesdan 	for (unsigned int i = 0; i < fpatterns; ++i) {
91d841ecb3SGabor Kovesdan 		if (fnmatch(fpattern[i].pat, fname, 0) == 0 ||
92ff415f05SKyle Evans 		    fnmatch(fpattern[i].pat, fname_base, 0) == 0)
93ff415f05SKyle Evans 			/*
94ff415f05SKyle Evans 			 * The last pattern matched wins exclusion/inclusion
95ff415f05SKyle Evans 			 * rights, so we can't reasonably bail out early here.
96ff415f05SKyle Evans 			 */
97e3a2abadSKyle Evans 			ret = (fpattern[i].mode != EXCL_PAT);
9855e44f51SGabor Kovesdan 	}
9933f5799aSEd Schouten 	free(fname_buf);
10055e44f51SGabor Kovesdan 	return (ret);
10155e44f51SGabor Kovesdan }
10255e44f51SGabor Kovesdan 
10359218eb7SGabor Kovesdan static inline bool
dir_matching(const char * dname)10455e44f51SGabor Kovesdan dir_matching(const char *dname)
10555e44f51SGabor Kovesdan {
10655e44f51SGabor Kovesdan 	bool ret;
10755e44f51SGabor Kovesdan 
10855e44f51SGabor Kovesdan 	ret = dinclude ? false : true;
10955e44f51SGabor Kovesdan 
11055e44f51SGabor Kovesdan 	for (unsigned int i = 0; i < dpatterns; ++i) {
111e3a2abadSKyle Evans 		if (dname != NULL && fnmatch(dpattern[i].pat, dname, 0) == 0)
112ff415f05SKyle Evans 			/*
113ff415f05SKyle Evans 			 * The last pattern matched wins exclusion/inclusion
114ff415f05SKyle Evans 			 * rights, so we can't reasonably bail out early here.
115ff415f05SKyle Evans 			 */
116ff415f05SKyle Evans 			ret = (dpattern[i].mode != EXCL_PAT);
11755e44f51SGabor Kovesdan 	}
11855e44f51SGabor Kovesdan 	return (ret);
11955e44f51SGabor Kovesdan }
12055e44f51SGabor Kovesdan 
1214dc88ebeSGabor Kovesdan /*
1224dc88ebeSGabor Kovesdan  * Processes a directory when a recursive search is performed with
1234dc88ebeSGabor Kovesdan  * the -R option.  Each appropriate file is passed to procfile().
1244dc88ebeSGabor Kovesdan  */
125cbfff13fSKyle Evans bool
grep_tree(char ** argv)1264dc88ebeSGabor Kovesdan grep_tree(char **argv)
1274dc88ebeSGabor Kovesdan {
1284dc88ebeSGabor Kovesdan 	FTS *fts;
1294dc88ebeSGabor Kovesdan 	FTSENT *p;
13040f0e0b1SKyle Evans 	int fts_flags;
131cbfff13fSKyle Evans 	bool matched, ok;
132a461896aSEd Maste 	const char *wd[] = { ".", NULL };
1334dc88ebeSGabor Kovesdan 
134cbfff13fSKyle Evans 	matched = false;
1354dc88ebeSGabor Kovesdan 
13666f780aeSKyle Evans 	/* This switch effectively initializes 'fts_flags' */
1374dc88ebeSGabor Kovesdan 	switch(linkbehave) {
1384dc88ebeSGabor Kovesdan 	case LINK_EXPLICIT:
13977eb8777SJohn Baldwin 		fts_flags = FTS_COMFOLLOW | FTS_PHYSICAL;
1404dc88ebeSGabor Kovesdan 		break;
1414dc88ebeSGabor Kovesdan 	case LINK_SKIP:
1424dc88ebeSGabor Kovesdan 		fts_flags = FTS_PHYSICAL;
1434dc88ebeSGabor Kovesdan 		break;
1444dc88ebeSGabor Kovesdan 	default:
14577eb8777SJohn Baldwin 		fts_flags = FTS_LOGICAL | FTS_NOSTAT;
1464dc88ebeSGabor Kovesdan 	}
1474dc88ebeSGabor Kovesdan 
14877eb8777SJohn Baldwin 	fts_flags |= FTS_NOCHDIR;
1494dc88ebeSGabor Kovesdan 
150a461896aSEd Maste 	fts = fts_open((argv[0] == NULL) ?
151a461896aSEd Maste 	    __DECONST(char * const *, wd) : argv, fts_flags, NULL);
152a461896aSEd Maste 	if (fts == NULL)
1530c41ffb3SXin LI 		err(2, "fts_open");
1542dfa4b66SBryan Drewery 	while (errno = 0, (p = fts_read(fts)) != NULL) {
1554dc88ebeSGabor Kovesdan 		switch (p->fts_info) {
1564dc88ebeSGabor Kovesdan 		case FTS_DNR:
1574dc88ebeSGabor Kovesdan 		case FTS_ERR:
15877eb8777SJohn Baldwin 		case FTS_NS:
1596f4cbf7cSGabor Kovesdan 			file_err = true;
160ede01be2SGabor Kovesdan 			if(!sflag)
16177eb8777SJohn Baldwin 				warnc(p->fts_errno, "%s", p->fts_path);
1624dc88ebeSGabor Kovesdan 			break;
1634dc88ebeSGabor Kovesdan 		case FTS_D:
164ad92276eSGabor Kovesdan 			if (dexclude || dinclude)
165ad92276eSGabor Kovesdan 				if (!dir_matching(p->fts_name) ||
166ad92276eSGabor Kovesdan 				    !dir_matching(p->fts_path))
167ad92276eSGabor Kovesdan 					fts_set(fts, p, FTS_SKIP);
1684dc88ebeSGabor Kovesdan 			break;
1694dc88ebeSGabor Kovesdan 		case FTS_DC:
1704dc88ebeSGabor Kovesdan 			/* Print a warning for recursive directory loop */
1714dc88ebeSGabor Kovesdan 			warnx("warning: %s: recursive directory loop",
1724dc88ebeSGabor Kovesdan 			    p->fts_path);
1734dc88ebeSGabor Kovesdan 			break;
17477eb8777SJohn Baldwin 		case FTS_DP:
17577eb8777SJohn Baldwin 			break;
17677eb8777SJohn Baldwin 		case FTS_SL:
17777eb8777SJohn Baldwin 			/*
17877eb8777SJohn Baldwin 			 * Skip symlinks for LINK_EXPLICIT and
17977eb8777SJohn Baldwin 			 * LINK_SKIP.  Note that due to FTS_COMFOLLOW,
18077eb8777SJohn Baldwin 			 * symlinks on the command line are followed
18177eb8777SJohn Baldwin 			 * for LINK_EXPLICIT and not reported as
18277eb8777SJohn Baldwin 			 * symlinks.
18377eb8777SJohn Baldwin 			 */
18477eb8777SJohn Baldwin 			break;
1854dc88ebeSGabor Kovesdan 		default:
1864dc88ebeSGabor Kovesdan 			/* Check for file exclusion/inclusion */
1874dc88ebeSGabor Kovesdan 			ok = true;
18855e44f51SGabor Kovesdan 			if (fexclude || finclude)
18955e44f51SGabor Kovesdan 				ok &= file_matching(p->fts_path);
1904dc88ebeSGabor Kovesdan 
191cbfff13fSKyle Evans 			if (ok && procfile(p->fts_path))
192cbfff13fSKyle Evans 				matched = true;
1934dc88ebeSGabor Kovesdan 			break;
1944dc88ebeSGabor Kovesdan 		}
1954dc88ebeSGabor Kovesdan 	}
1962dfa4b66SBryan Drewery 	if (errno != 0)
1972dfa4b66SBryan Drewery 		err(2, "fts_read");
1984dc88ebeSGabor Kovesdan 
1990c41ffb3SXin LI 	fts_close(fts);
200cbfff13fSKyle Evans 	return (matched);
2014dc88ebeSGabor Kovesdan }
2024dc88ebeSGabor Kovesdan 
203042db8e8SKyle Evans static void
procmatch_match(struct mprintc * mc,struct parsec * pc)204042db8e8SKyle Evans procmatch_match(struct mprintc *mc, struct parsec *pc)
20581c634e8SKyle Evans {
20681c634e8SKyle Evans 
2075ea3fdc7SKyle Evans 	if (mc->doctx) {
208042db8e8SKyle Evans 		if (!first_match && (!mc->same_file || mc->last_outed > 0))
20981c634e8SKyle Evans 			printf("--\n");
21081c634e8SKyle Evans 		if (Bflag > 0)
21181c634e8SKyle Evans 			printqueue();
21281c634e8SKyle Evans 		mc->tail = Aflag;
21381c634e8SKyle Evans 	}
21481c634e8SKyle Evans 
21581c634e8SKyle Evans 	/* Print the matching line, but only if not quiet/binary */
2165ea3fdc7SKyle Evans 	if (mc->printmatch) {
217*4c9ffb13SKyle Evans 		size_t last_out;
218*4c9ffb13SKyle Evans 		bool terminated;
219*4c9ffb13SKyle Evans 
220*4c9ffb13SKyle Evans 		last_out = 0;
221*4c9ffb13SKyle Evans 		terminated = printline(pc, ':', &last_out);
22281c634e8SKyle Evans 		while (pc->matchidx >= MAX_MATCHES) {
22381c634e8SKyle Evans 			/* Reset matchidx and try again */
22481c634e8SKyle Evans 			pc->matchidx = 0;
22538325e2aSKyle Evans 			if (procline(pc) == !vflag)
226*4c9ffb13SKyle Evans 				terminated = printline(pc, ':', &last_out);
22781c634e8SKyle Evans 			else
22881c634e8SKyle Evans 				break;
22981c634e8SKyle Evans 		}
230*4c9ffb13SKyle Evans 
231*4c9ffb13SKyle Evans 		/*
232*4c9ffb13SKyle Evans 		 * The above loop processes the entire line as long as we keep
233*4c9ffb13SKyle Evans 		 * hitting the maximum match count.  At this point, we know
234*4c9ffb13SKyle Evans 		 * that there's nothing left to be printed and can terminate the
235*4c9ffb13SKyle Evans 		 * line.
236*4c9ffb13SKyle Evans 		 */
237*4c9ffb13SKyle Evans 		if (!terminated)
238*4c9ffb13SKyle Evans 			printline(pc, ':', &last_out);
239*4c9ffb13SKyle Evans 
24081c634e8SKyle Evans 		first_match = false;
24181c634e8SKyle Evans 		mc->same_file = true;
24281c634e8SKyle Evans 		mc->last_outed = 0;
24381c634e8SKyle Evans 	}
244042db8e8SKyle Evans }
245042db8e8SKyle Evans 
246042db8e8SKyle Evans static void
procmatch_nomatch(struct mprintc * mc,struct parsec * pc)247042db8e8SKyle Evans procmatch_nomatch(struct mprintc *mc, struct parsec *pc)
248042db8e8SKyle Evans {
249042db8e8SKyle Evans 
250042db8e8SKyle Evans 	/* Deal with any -A context as needed */
251042db8e8SKyle Evans 	if (mc->tail > 0) {
252042db8e8SKyle Evans 		grep_printline(&pc->ln, '-');
253042db8e8SKyle Evans 		mc->tail--;
254042db8e8SKyle Evans 		if (Bflag > 0)
255042db8e8SKyle Evans 			clearqueue();
256042db8e8SKyle Evans 	} else if (Bflag == 0 || (Bflag > 0 && enqueue(&pc->ln)))
257042db8e8SKyle Evans 		/*
258042db8e8SKyle Evans 		 * Enqueue non-matching lines for -B context. If we're not
259042db8e8SKyle Evans 		 * actually doing -B context or if the enqueue resulted in a
260042db8e8SKyle Evans 		 * line being rotated out, then go ahead and increment
261042db8e8SKyle Evans 		 * last_outed to signify a gap between context/match.
262042db8e8SKyle Evans 		 */
263042db8e8SKyle Evans 		++mc->last_outed;
264042db8e8SKyle Evans }
265042db8e8SKyle Evans 
266042db8e8SKyle Evans /*
267042db8e8SKyle Evans  * Process any matches in the current parsing context, return a boolean
268042db8e8SKyle Evans  * indicating whether we should halt any further processing or not. 'true' to
269042db8e8SKyle Evans  * continue processing, 'false' to halt.
270042db8e8SKyle Evans  */
271042db8e8SKyle Evans static bool
procmatches(struct mprintc * mc,struct parsec * pc,bool matched)272042db8e8SKyle Evans procmatches(struct mprintc *mc, struct parsec *pc, bool matched)
273042db8e8SKyle Evans {
274042db8e8SKyle Evans 
2753e2d96acSKyle Evans 	if (mflag && mcount <= 0) {
2763e2d96acSKyle Evans 		/*
2773e2d96acSKyle Evans 		 * We already hit our match count, but we need to keep dumping
2783e2d96acSKyle Evans 		 * lines until we've lost our tail.
2793e2d96acSKyle Evans 		 */
2803e2d96acSKyle Evans 		grep_printline(&pc->ln, '-');
2813e2d96acSKyle Evans 		mc->tail--;
2823e2d96acSKyle Evans 		return (mc->tail != 0);
2833e2d96acSKyle Evans 	}
2843e2d96acSKyle Evans 
285042db8e8SKyle Evans 	/*
286042db8e8SKyle Evans 	 * XXX TODO: This should loop over pc->matches and handle things on a
287042db8e8SKyle Evans 	 * line-by-line basis, setting up a `struct str` as needed.
288042db8e8SKyle Evans 	 */
289042db8e8SKyle Evans 	/* Deal with any -B context or context separators */
290042db8e8SKyle Evans 	if (matched) {
291042db8e8SKyle Evans 		procmatch_match(mc, pc);
29281c634e8SKyle Evans 
2935ea3fdc7SKyle Evans 		/* Count the matches if we have a match limit */
2945ea3fdc7SKyle Evans 		if (mflag) {
2955ea3fdc7SKyle Evans 			/* XXX TODO: Decrement by number of matched lines */
2965ea3fdc7SKyle Evans 			mcount -= 1;
297bd60b9b4SKyle Evans 			if (mcount <= 0)
2983e2d96acSKyle Evans 				return (mc->tail != 0);
2995ea3fdc7SKyle Evans 		}
300042db8e8SKyle Evans 	} else if (mc->doctx)
301042db8e8SKyle Evans 		procmatch_nomatch(mc, pc);
30281c634e8SKyle Evans 
30381c634e8SKyle Evans 	return (true);
30481c634e8SKyle Evans }
30581c634e8SKyle Evans 
30681c634e8SKyle Evans /*
3074dc88ebeSGabor Kovesdan  * Opens a file and processes it.  Each file is processed line-by-line
3084dc88ebeSGabor Kovesdan  * passing the lines to procline().
3094dc88ebeSGabor Kovesdan  */
310cbfff13fSKyle Evans bool
procfile(const char * fn)3114dc88ebeSGabor Kovesdan procfile(const char *fn)
3124dc88ebeSGabor Kovesdan {
313a4f3f02bSEd Maste 	struct parsec pc;
31481c634e8SKyle Evans 	struct mprintc mc;
3154dc88ebeSGabor Kovesdan 	struct file *f;
3164dc88ebeSGabor Kovesdan 	struct stat sb;
3174dc88ebeSGabor Kovesdan 	mode_t s;
318be13c0f9SKyle Evans 	int lines;
319be13c0f9SKyle Evans 	bool line_matched;
3204dc88ebeSGabor Kovesdan 
3214dc88ebeSGabor Kovesdan 	if (strcmp(fn, "-") == 0) {
32230dc9502SBaptiste Daroussin 		fn = label != NULL ? label : errstr[1];
3233ed1008bSGabor Kovesdan 		f = grep_open(NULL);
3244dc88ebeSGabor Kovesdan 	} else {
325f3cf3e59SKyle Evans 		if (stat(fn, &sb) == 0) {
3264dc88ebeSGabor Kovesdan 			/* Check if we need to process the file */
3274dc88ebeSGabor Kovesdan 			s = sb.st_mode & S_IFMT;
328f3cf3e59SKyle Evans 			if (dirbehave == DIR_SKIP && s == S_IFDIR)
329cbfff13fSKyle Evans 				return (false);
330f3cf3e59SKyle Evans 			if (devbehave == DEV_SKIP && (s == S_IFIFO ||
331f3cf3e59SKyle Evans 			    s == S_IFCHR || s == S_IFBLK || s == S_IFSOCK))
332cbfff13fSKyle Evans 				return (false);
3334dc88ebeSGabor Kovesdan 		}
3344dc88ebeSGabor Kovesdan 		f = grep_open(fn);
3354dc88ebeSGabor Kovesdan 	}
3364dc88ebeSGabor Kovesdan 	if (f == NULL) {
3376f4cbf7cSGabor Kovesdan 		file_err = true;
3384dc88ebeSGabor Kovesdan 		if (!sflag)
3394dc88ebeSGabor Kovesdan 			warn("%s", fn);
340cbfff13fSKyle Evans 		return (false);
3414dc88ebeSGabor Kovesdan 	}
3424dc88ebeSGabor Kovesdan 
34366ab2983SKyle Evans 	pc.ln.file = grep_strdup(fn);
344a4f3f02bSEd Maste 	pc.ln.line_no = 0;
345a4f3f02bSEd Maste 	pc.ln.len = 0;
3466d635d3bSEd Maste 	pc.ln.boff = 0;
347a4f3f02bSEd Maste 	pc.ln.off = -1;
348a4f3f02bSEd Maste 	pc.binary = f->binary;
349bd60b9b4SKyle Evans 	pc.cntlines = false;
35081c634e8SKyle Evans 	memset(&mc, 0, sizeof(mc));
35181c634e8SKyle Evans 	mc.printmatch = true;
352e2127de8SEd Maste 	if ((pc.binary && binbehave == BINFILE_BIN) || cflag || qflag ||
353e2127de8SEd Maste 	    lflag || Lflag)
35481c634e8SKyle Evans 		mc.printmatch = false;
35581c634e8SKyle Evans 	if (mc.printmatch && (Aflag != 0 || Bflag != 0))
35681c634e8SKyle Evans 		mc.doctx = true;
357bd60b9b4SKyle Evans 	if (mc.printmatch && (Aflag != 0 || Bflag != 0 || mflag || nflag))
358bd60b9b4SKyle Evans 		pc.cntlines = true;
35983fd8885SEd Maste 	mcount = mlimit;
36083fd8885SEd Maste 
361cbfff13fSKyle Evans 	for (lines = 0; lines == 0 || !(lflag || qflag); ) {
362d83f17e5SKyle Evans 		/*
363d83f17e5SKyle Evans 		 * XXX TODO: We need to revisit this in a chunking world. We're
364d83f17e5SKyle Evans 		 * not going to be doing per-line statistics because of the
365d83f17e5SKyle Evans 		 * overhead involved. procmatches can figure that stuff out as
366d83f17e5SKyle Evans 		 * needed. */
3676d635d3bSEd Maste 		/* Reset per-line statistics */
3686d635d3bSEd Maste 		pc.printed = 0;
369a4f3f02bSEd Maste 		pc.matchidx = 0;
370fe8c9d5bSEd Maste 		pc.lnstart = 0;
3716d635d3bSEd Maste 		pc.ln.boff = 0;
372a4f3f02bSEd Maste 		pc.ln.off += pc.ln.len + 1;
373d83f17e5SKyle Evans 		/* XXX TODO: Grab a chunk */
374bd60b9b4SKyle Evans 		if ((pc.ln.dat = grep_fgetln(f, &pc)) == NULL ||
3750e957942SKyle Evans 		    pc.ln.len == 0)
3764dc88ebeSGabor Kovesdan 			break;
377a4f3f02bSEd Maste 
378a4f3f02bSEd Maste 		if (pc.ln.len > 0 && pc.ln.dat[pc.ln.len - 1] == fileeol)
379a4f3f02bSEd Maste 			--pc.ln.len;
380a4f3f02bSEd Maste 		pc.ln.line_no++;
3814dc88ebeSGabor Kovesdan 
3824dc88ebeSGabor Kovesdan 		/* Return if we need to skip a binary file */
383a4f3f02bSEd Maste 		if (pc.binary && binbehave == BINFILE_SKIP) {
3844dc88ebeSGabor Kovesdan 			grep_close(f);
385a4f3f02bSEd Maste 			free(pc.ln.file);
3864dc88ebeSGabor Kovesdan 			free(f);
3874dc88ebeSGabor Kovesdan 			return (0);
3884dc88ebeSGabor Kovesdan 		}
38922130a21SEd Maste 
3903e2d96acSKyle Evans 		if (mflag && mcount <= 0) {
3913e2d96acSKyle Evans 			/*
3923e2d96acSKyle Evans 			 * Short-circuit, already hit match count and now we're
3933e2d96acSKyle Evans 			 * just picking up any remaining pieces.
3943e2d96acSKyle Evans 			 */
3953e2d96acSKyle Evans 			if (!procmatches(&mc, &pc, false))
3963e2d96acSKyle Evans 				break;
3973e2d96acSKyle Evans 			continue;
3983e2d96acSKyle Evans 		}
39938325e2aSKyle Evans 		line_matched = procline(&pc) == !vflag;
400be13c0f9SKyle Evans 		if (line_matched)
401cbfff13fSKyle Evans 			++lines;
402a4f3f02bSEd Maste 
40381c634e8SKyle Evans 		/* Halt processing if we hit our match limit */
404be13c0f9SKyle Evans 		if (!procmatches(&mc, &pc, line_matched))
405fe8c9d5bSEd Maste 			break;
406fe8c9d5bSEd Maste 	}
4074dc88ebeSGabor Kovesdan 	if (Bflag > 0)
4084dc88ebeSGabor Kovesdan 		clearqueue();
4094dc88ebeSGabor Kovesdan 	grep_close(f);
4104dc88ebeSGabor Kovesdan 
41124c681a7SMariusz Zaborski 	if (cflag && !qflag) {
4124dc88ebeSGabor Kovesdan 		if (!hflag)
413a4f3f02bSEd Maste 			printf("%s:", pc.ln.file);
414cbfff13fSKyle Evans 		printf("%u\n", lines);
4154dc88ebeSGabor Kovesdan 	}
416cbfff13fSKyle Evans 	if (lflag && !qflag && lines != 0)
417f0c94259SGabor Kovesdan 		printf("%s%c", fn, nullflag ? 0 : '\n');
418cbfff13fSKyle Evans 	if (Lflag && !qflag && lines == 0)
419f0c94259SGabor Kovesdan 		printf("%s%c", fn, nullflag ? 0 : '\n');
420cbfff13fSKyle Evans 	if (lines != 0 && !cflag && !lflag && !Lflag &&
4214dc88ebeSGabor Kovesdan 	    binbehave == BINFILE_BIN && f->binary && !qflag)
42230dc9502SBaptiste Daroussin 		printf(errstr[7], fn);
4234dc88ebeSGabor Kovesdan 
424a4f3f02bSEd Maste 	free(pc.ln.file);
4254dc88ebeSGabor Kovesdan 	free(f);
426cbfff13fSKyle Evans 	return (lines != 0);
4274dc88ebeSGabor Kovesdan }
4284dc88ebeSGabor Kovesdan 
42905ad8215SKyle Evans #ifdef WITH_INTERNAL_NOSPEC
43005ad8215SKyle Evans /*
43105ad8215SKyle Evans  * Internal implementation of literal string search within a string, modeled
43205ad8215SKyle Evans  * after regexec(3), for use when the regex(3) implementation doesn't offer
43305ad8215SKyle Evans  * either REG_NOSPEC or REG_LITERAL. This does not apply in the default FreeBSD
43405ad8215SKyle Evans  * config, but in other scenarios such as building against libgnuregex or on
43505ad8215SKyle Evans  * some non-FreeBSD OSes.
43605ad8215SKyle Evans  */
43705ad8215SKyle Evans static int
litexec(const struct pat * pat,const char * string,size_t nmatch,regmatch_t pmatch[])43805ad8215SKyle Evans litexec(const struct pat *pat, const char *string, size_t nmatch,
43905ad8215SKyle Evans     regmatch_t pmatch[])
44005ad8215SKyle Evans {
44105ad8215SKyle Evans 	char *(*strstr_fn)(const char *, const char *);
44205ad8215SKyle Evans 	char *sub, *subject;
44305ad8215SKyle Evans 	const char *search;
44405ad8215SKyle Evans 	size_t idx, n, ofs, stringlen;
44505ad8215SKyle Evans 
44605ad8215SKyle Evans 	if (cflags & REG_ICASE)
44705ad8215SKyle Evans 		strstr_fn = strcasestr;
44805ad8215SKyle Evans 	else
44905ad8215SKyle Evans 		strstr_fn = strstr;
45005ad8215SKyle Evans 	idx = 0;
45105ad8215SKyle Evans 	ofs = pmatch[0].rm_so;
45205ad8215SKyle Evans 	stringlen = pmatch[0].rm_eo;
45305ad8215SKyle Evans 	if (ofs >= stringlen)
45405ad8215SKyle Evans 		return (REG_NOMATCH);
45505ad8215SKyle Evans 	subject = strndup(string, stringlen);
45605ad8215SKyle Evans 	if (subject == NULL)
45705ad8215SKyle Evans 		return (REG_ESPACE);
45805ad8215SKyle Evans 	for (n = 0; ofs < stringlen;) {
45905ad8215SKyle Evans 		search = (subject + ofs);
46005ad8215SKyle Evans 		if ((unsigned long)pat->len > strlen(search))
46105ad8215SKyle Evans 			break;
46205ad8215SKyle Evans 		sub = strstr_fn(search, pat->pat);
46305ad8215SKyle Evans 		/*
46405ad8215SKyle Evans 		 * Ignoring the empty string possibility due to context: grep optimizes
46505ad8215SKyle Evans 		 * for empty patterns and will never reach this point.
46605ad8215SKyle Evans 		 */
46705ad8215SKyle Evans 		if (sub == NULL)
46805ad8215SKyle Evans 			break;
46905ad8215SKyle Evans 		++n;
47005ad8215SKyle Evans 		/* Fill in pmatch if necessary */
47105ad8215SKyle Evans 		if (nmatch > 0) {
47205ad8215SKyle Evans 			pmatch[idx].rm_so = ofs + (sub - search);
47305ad8215SKyle Evans 			pmatch[idx].rm_eo = pmatch[idx].rm_so + pat->len;
47405ad8215SKyle Evans 			if (++idx == nmatch)
47505ad8215SKyle Evans 				break;
47605ad8215SKyle Evans 			ofs = pmatch[idx].rm_so + 1;
47705ad8215SKyle Evans 		} else
47805ad8215SKyle Evans 			/* We only needed to know if we match or not */
47905ad8215SKyle Evans 			break;
48005ad8215SKyle Evans 	}
48105ad8215SKyle Evans 	free(subject);
48205ad8215SKyle Evans 	if (n > 0 && nmatch > 0)
48305ad8215SKyle Evans 		for (n = idx; n < nmatch; ++n)
48405ad8215SKyle Evans 			pmatch[n].rm_so = pmatch[n].rm_eo = -1;
48505ad8215SKyle Evans 
48605ad8215SKyle Evans 	return (n > 0 ? 0 : REG_NOMATCH);
48705ad8215SKyle Evans }
48805ad8215SKyle Evans #endif /* WITH_INTERNAL_NOSPEC */
48905ad8215SKyle Evans 
4904dc88ebeSGabor Kovesdan #define iswword(x)	(iswalnum((x)) || (x) == L'_')
4914dc88ebeSGabor Kovesdan 
4924dc88ebeSGabor Kovesdan /*
4934dc88ebeSGabor Kovesdan  * Processes a line comparing it with the specified patterns.  Each pattern
4944dc88ebeSGabor Kovesdan  * is looped to be compared along with the full string, saving each and every
4954dc88ebeSGabor Kovesdan  * match, which is necessary to colorize the output and to count the
4964dc88ebeSGabor Kovesdan  * matches.  The matching lines are passed to printline() to display the
4974dc88ebeSGabor Kovesdan  * appropriate output.
4984dc88ebeSGabor Kovesdan  */
499be13c0f9SKyle Evans static bool
procline(struct parsec * pc)500a4f3f02bSEd Maste procline(struct parsec *pc)
5014dc88ebeSGabor Kovesdan {
502a4f3f02bSEd Maste 	regmatch_t pmatch, lastmatch, chkmatch;
503a4f3f02bSEd Maste 	wchar_t wbegin, wend;
504fe8c9d5bSEd Maste 	size_t st, nst;
5054dc88ebeSGabor Kovesdan 	unsigned int i;
506be13c0f9SKyle Evans 	int r = 0, leflags = eflags;
507a4f3f02bSEd Maste 	size_t startm = 0, matchidx;
508fe8c9d5bSEd Maste 	unsigned int retry;
509be13c0f9SKyle Evans 	bool lastmatched, matched;
5104dc88ebeSGabor Kovesdan 
511a4f3f02bSEd Maste 	matchidx = pc->matchidx;
512a4f3f02bSEd Maste 
513f823c6dcSKyle Evans 	/* Null pattern shortcuts. */
51438325e2aSKyle Evans 	if (matchall) {
515f823c6dcSKyle Evans 		if (xflag && pc->ln.len == 0) {
516f823c6dcSKyle Evans 			/* Matches empty lines (-x). */
517be13c0f9SKyle Evans 			return (true);
518f823c6dcSKyle Evans 		} else if (!wflag && !xflag) {
519f823c6dcSKyle Evans 			/* Matches every line (no -w or -x). */
52038325e2aSKyle Evans 			return (true);
521f823c6dcSKyle Evans 		}
52238325e2aSKyle Evans 
52338325e2aSKyle Evans 		/*
524f823c6dcSKyle Evans 		 * If we only have the NULL pattern, whether we match or not
525f823c6dcSKyle Evans 		 * depends on if we got here with -w or -x.  If either is set,
526f823c6dcSKyle Evans 		 * the answer is no.  If we have other patterns, we'll defer
527f823c6dcSKyle Evans 		 * to them.
52838325e2aSKyle Evans 		 */
529f823c6dcSKyle Evans 		if (patterns == 0) {
530f823c6dcSKyle Evans 			return (!(wflag || xflag));
531f823c6dcSKyle Evans 		}
532f823c6dcSKyle Evans 	} else if (patterns == 0) {
533f823c6dcSKyle Evans 		/* Pattern file with no patterns. */
534be13c0f9SKyle Evans 		return (false);
53538325e2aSKyle Evans 	}
536a4f3f02bSEd Maste 
537be13c0f9SKyle Evans 	matched = false;
538fe8c9d5bSEd Maste 	st = pc->lnstart;
539fe8c9d5bSEd Maste 	nst = 0;
540a734ae9cSEd Maste 	/* Initialize to avoid a false positive warning from GCC. */
541a734ae9cSEd Maste 	lastmatch.rm_so = lastmatch.rm_eo = 0;
542a734ae9cSEd Maste 
5434dc88ebeSGabor Kovesdan 	/* Loop to process the whole line */
544a4f3f02bSEd Maste 	while (st <= pc->ln.len) {
545be13c0f9SKyle Evans 		lastmatched = false;
546a4f3f02bSEd Maste 		startm = matchidx;
547945fc991SEd Maste 		retry = 0;
5488bf46064SEd Maste 		if (st > 0 && pc->ln.dat[st - 1] != fileeol)
54987c485cfSEd Maste 			leflags |= REG_NOTBOL;
5504dc88ebeSGabor Kovesdan 		/* Loop to compare with all the patterns */
5514dc88ebeSGabor Kovesdan 		for (i = 0; i < patterns; i++) {
55287c485cfSEd Maste 			pmatch.rm_so = st;
553a4f3f02bSEd Maste 			pmatch.rm_eo = pc->ln.len;
55405ad8215SKyle Evans #ifdef WITH_INTERNAL_NOSPEC
55505ad8215SKyle Evans 			if (grepbehave == GREP_FIXED)
55605ad8215SKyle Evans 				r = litexec(&pattern[i], pc->ln.dat, 1, &pmatch);
55705ad8215SKyle Evans 			else
55805ad8215SKyle Evans #endif
559a2584d1bSKyle Evans 			r = regexec(&r_pattern[i], pc->ln.dat, 1, &pmatch,
560a2584d1bSKyle Evans 			    leflags);
561a4f3f02bSEd Maste 			if (r != 0)
5624dc88ebeSGabor Kovesdan 				continue;
5634dc88ebeSGabor Kovesdan 			/* Check for full match */
564a4f3f02bSEd Maste 			if (xflag && (pmatch.rm_so != 0 ||
565a4f3f02bSEd Maste 			    (size_t)pmatch.rm_eo != pc->ln.len))
566a4f3f02bSEd Maste 				continue;
5674dc88ebeSGabor Kovesdan 			/* Check for whole word match */
568a4f3f02bSEd Maste 			if (wflag) {
56959218eb7SGabor Kovesdan 				wbegin = wend = L' ';
57059218eb7SGabor Kovesdan 				if (pmatch.rm_so != 0 &&
571a4f3f02bSEd Maste 				    sscanf(&pc->ln.dat[pmatch.rm_so - 1],
57259218eb7SGabor Kovesdan 				    "%lc", &wbegin) != 1)
5734dc88ebeSGabor Kovesdan 					r = REG_NOMATCH;
574cbe6b9e5SGabor Kovesdan 				else if ((size_t)pmatch.rm_eo !=
575a4f3f02bSEd Maste 				    pc->ln.len &&
576a4f3f02bSEd Maste 				    sscanf(&pc->ln.dat[pmatch.rm_eo],
5774dc88ebeSGabor Kovesdan 				    "%lc", &wend) != 1)
5784dc88ebeSGabor Kovesdan 					r = REG_NOMATCH;
579cbe6b9e5SGabor Kovesdan 				else if (iswword(wbegin) ||
580cbe6b9e5SGabor Kovesdan 				    iswword(wend))
5814dc88ebeSGabor Kovesdan 					r = REG_NOMATCH;
582945fc991SEd Maste 				/*
583945fc991SEd Maste 				 * If we're doing whole word matching and we
584945fc991SEd Maste 				 * matched once, then we should try the pattern
585945fc991SEd Maste 				 * again after advancing just past the start of
586945fc991SEd Maste 				 * the earliest match. This allows the pattern
587945fc991SEd Maste 				 * to  match later on in the line and possibly
588945fc991SEd Maste 				 * still match a whole word.
589945fc991SEd Maste 				 */
590945fc991SEd Maste 				if (r == REG_NOMATCH &&
591fe8c9d5bSEd Maste 				    (retry == pc->lnstart ||
592de3d7a82SKyle Evans 				    (unsigned int)pmatch.rm_so + 1 < retry))
593945fc991SEd Maste 					retry = pmatch.rm_so + 1;
594a4f3f02bSEd Maste 				if (r == REG_NOMATCH)
595a4f3f02bSEd Maste 					continue;
5964dc88ebeSGabor Kovesdan 			}
597be13c0f9SKyle Evans 			lastmatched = true;
59887c485cfSEd Maste 			lastmatch = pmatch;
599a4f3f02bSEd Maste 
600a4f3f02bSEd Maste 			if (matchidx == 0)
601be13c0f9SKyle Evans 				matched = true;
60287c485cfSEd Maste 
603a4f3f02bSEd Maste 			/*
604a4f3f02bSEd Maste 			 * Replace previous match if the new one is earlier
605a4f3f02bSEd Maste 			 * and/or longer. This will lead to some amount of
606a4f3f02bSEd Maste 			 * extra work if -o/--color are specified, but it's
607a4f3f02bSEd Maste 			 * worth it from a correctness point of view.
608a4f3f02bSEd Maste 			 */
609a4f3f02bSEd Maste 			if (matchidx > startm) {
610a4f3f02bSEd Maste 				chkmatch = pc->matches[matchidx - 1];
611a4f3f02bSEd Maste 				if (pmatch.rm_so < chkmatch.rm_so ||
612a4f3f02bSEd Maste 				    (pmatch.rm_so == chkmatch.rm_so &&
613a4f3f02bSEd Maste 				    (pmatch.rm_eo - pmatch.rm_so) >
614a4f3f02bSEd Maste 				    (chkmatch.rm_eo - chkmatch.rm_so))) {
615a4f3f02bSEd Maste 					pc->matches[matchidx - 1] = pmatch;
61687c485cfSEd Maste 					nst = pmatch.rm_eo;
61787c485cfSEd Maste 				}
61887c485cfSEd Maste 			} else {
61987c485cfSEd Maste 				/* Advance as normal if not */
620a4f3f02bSEd Maste 				pc->matches[matchidx++] = pmatch;
62187c485cfSEd Maste 				nst = pmatch.rm_eo;
62287c485cfSEd Maste 			}
623a4f3f02bSEd Maste 			/* avoid excessive matching - skip further patterns */
624a4f3f02bSEd Maste 			if ((color == NULL && !oflag) || qflag || lflag ||
6258bf46064SEd Maste 			    matchidx >= MAX_MATCHES) {
626fe8c9d5bSEd Maste 				pc->lnstart = nst;
627be13c0f9SKyle Evans 				lastmatched = false;
6284dc88ebeSGabor Kovesdan 				break;
6294dc88ebeSGabor Kovesdan 			}
630fe8c9d5bSEd Maste 		}
6314dc88ebeSGabor Kovesdan 
632945fc991SEd Maste 		/*
633945fc991SEd Maste 		 * Advance to just past the start of the earliest match, try
634945fc991SEd Maste 		 * again just in case we still have a chance to match later in
635945fc991SEd Maste 		 * the string.
636945fc991SEd Maste 		 */
637be13c0f9SKyle Evans 		if (!lastmatched && retry > pc->lnstart) {
638945fc991SEd Maste 			st = retry;
639945fc991SEd Maste 			continue;
6404dc88ebeSGabor Kovesdan 		}
641f20f6f3fSGabor Kovesdan 
642d83f17e5SKyle Evans 		/* XXX TODO: We will need to keep going, since we're chunky */
6434dc88ebeSGabor Kovesdan 		/* One pass if we are not recording matches */
6442ac5b1c7SGabor Kovesdan 		if (!wflag && ((color == NULL && !oflag) || qflag || lflag || Lflag))
6454dc88ebeSGabor Kovesdan 			break;
6464dc88ebeSGabor Kovesdan 
64787c485cfSEd Maste 		/* If we didn't have any matches or REG_NOSUB set */
648be13c0f9SKyle Evans 		if (!lastmatched || (cflags & REG_NOSUB))
649a4f3f02bSEd Maste 			nst = pc->ln.len;
65087c485cfSEd Maste 
651be13c0f9SKyle Evans 		if (!lastmatched)
65287c485cfSEd Maste 			/* No matches */
65387c485cfSEd Maste 			break;
65487c485cfSEd Maste 		else if (st == nst && lastmatch.rm_so == lastmatch.rm_eo)
65587c485cfSEd Maste 			/* Zero-length match -- advance one more so we don't get stuck */
65687c485cfSEd Maste 			nst++;
65787c485cfSEd Maste 
65887c485cfSEd Maste 		/* Advance st based on previous matches */
65987c485cfSEd Maste 		st = nst;
660fe8c9d5bSEd Maste 		pc->lnstart = st;
6614dc88ebeSGabor Kovesdan 	}
662f20f6f3fSGabor Kovesdan 
663a4f3f02bSEd Maste 	/* Reflect the new matchidx in the context */
664a4f3f02bSEd Maste 	pc->matchidx = matchidx;
665be13c0f9SKyle Evans 	return matched;
6664dc88ebeSGabor Kovesdan }
6674dc88ebeSGabor Kovesdan 
6684dc88ebeSGabor Kovesdan /*
6694dc88ebeSGabor Kovesdan  * Safe malloc() for internal use.
6704dc88ebeSGabor Kovesdan  */
6714dc88ebeSGabor Kovesdan void *
grep_malloc(size_t size)6724dc88ebeSGabor Kovesdan grep_malloc(size_t size)
6734dc88ebeSGabor Kovesdan {
6744dc88ebeSGabor Kovesdan 	void *ptr;
6754dc88ebeSGabor Kovesdan 
676e116e040SKyle Evans 	if (size == 0)
677e116e040SKyle Evans 		return (NULL);
6784dc88ebeSGabor Kovesdan 	if ((ptr = malloc(size)) == NULL)
6794dc88ebeSGabor Kovesdan 		err(2, "malloc");
6804dc88ebeSGabor Kovesdan 	return (ptr);
6814dc88ebeSGabor Kovesdan }
6824dc88ebeSGabor Kovesdan 
6834dc88ebeSGabor Kovesdan /*
6844dc88ebeSGabor Kovesdan  * Safe calloc() for internal use.
6854dc88ebeSGabor Kovesdan  */
6864dc88ebeSGabor Kovesdan void *
grep_calloc(size_t nmemb,size_t size)6874dc88ebeSGabor Kovesdan grep_calloc(size_t nmemb, size_t size)
6884dc88ebeSGabor Kovesdan {
6894dc88ebeSGabor Kovesdan 	void *ptr;
6904dc88ebeSGabor Kovesdan 
691e116e040SKyle Evans 	if (nmemb == 0 || size == 0)
692e116e040SKyle Evans 		return (NULL);
6934dc88ebeSGabor Kovesdan 	if ((ptr = calloc(nmemb, size)) == NULL)
6944dc88ebeSGabor Kovesdan 		err(2, "calloc");
6954dc88ebeSGabor Kovesdan 	return (ptr);
6964dc88ebeSGabor Kovesdan }
6974dc88ebeSGabor Kovesdan 
6984dc88ebeSGabor Kovesdan /*
6994dc88ebeSGabor Kovesdan  * Safe realloc() for internal use.
7004dc88ebeSGabor Kovesdan  */
7014dc88ebeSGabor Kovesdan void *
grep_realloc(void * ptr,size_t size)7024dc88ebeSGabor Kovesdan grep_realloc(void *ptr, size_t size)
7034dc88ebeSGabor Kovesdan {
7044dc88ebeSGabor Kovesdan 
7054dc88ebeSGabor Kovesdan 	if ((ptr = realloc(ptr, size)) == NULL)
7064dc88ebeSGabor Kovesdan 		err(2, "realloc");
7074dc88ebeSGabor Kovesdan 	return (ptr);
7084dc88ebeSGabor Kovesdan }
7094dc88ebeSGabor Kovesdan 
7104dc88ebeSGabor Kovesdan /*
71155e44f51SGabor Kovesdan  * Safe strdup() for internal use.
71255e44f51SGabor Kovesdan  */
71355e44f51SGabor Kovesdan char *
grep_strdup(const char * str)71455e44f51SGabor Kovesdan grep_strdup(const char *str)
71555e44f51SGabor Kovesdan {
71655e44f51SGabor Kovesdan 	char *ret;
71755e44f51SGabor Kovesdan 
71855e44f51SGabor Kovesdan 	if ((ret = strdup(str)) == NULL)
71955e44f51SGabor Kovesdan 		err(2, "strdup");
72055e44f51SGabor Kovesdan 	return (ret);
72155e44f51SGabor Kovesdan }
72255e44f51SGabor Kovesdan 
72355e44f51SGabor Kovesdan /*
724a4f3f02bSEd Maste  * Print an entire line as-is, there are no inline matches to consider. This is
725a4f3f02bSEd Maste  * used for printing context.
7264dc88ebeSGabor Kovesdan  */
grep_printline(struct str * line,int sep)727a4f3f02bSEd Maste void grep_printline(struct str *line, int sep) {
728a4f3f02bSEd Maste 	printline_metadata(line, sep);
729a4f3f02bSEd Maste 	fwrite(line->dat, line->len, 1, stdout);
730a4f3f02bSEd Maste 	putchar(fileeol);
731a4f3f02bSEd Maste }
732a4f3f02bSEd Maste 
733a4f3f02bSEd Maste static void
printline_metadata(struct str * line,int sep)734a4f3f02bSEd Maste printline_metadata(struct str *line, int sep)
7354dc88ebeSGabor Kovesdan {
736a4f3f02bSEd Maste 	bool printsep;
7374dc88ebeSGabor Kovesdan 
738a4f3f02bSEd Maste 	printsep = false;
7394dc88ebeSGabor Kovesdan 	if (!hflag) {
740f0c94259SGabor Kovesdan 		if (!nullflag) {
7414dc88ebeSGabor Kovesdan 			fputs(line->file, stdout);
742a4f3f02bSEd Maste 			printsep = true;
743f0c94259SGabor Kovesdan 		} else {
7444dc88ebeSGabor Kovesdan 			printf("%s", line->file);
7454dc88ebeSGabor Kovesdan 			putchar(0);
7464dc88ebeSGabor Kovesdan 		}
7474dc88ebeSGabor Kovesdan 	}
7484dc88ebeSGabor Kovesdan 	if (nflag) {
749a4f3f02bSEd Maste 		if (printsep)
7504dc88ebeSGabor Kovesdan 			putchar(sep);
7514dc88ebeSGabor Kovesdan 		printf("%d", line->line_no);
752a4f3f02bSEd Maste 		printsep = true;
7534dc88ebeSGabor Kovesdan 	}
7544dc88ebeSGabor Kovesdan 	if (bflag) {
755a4f3f02bSEd Maste 		if (printsep)
7564dc88ebeSGabor Kovesdan 			putchar(sep);
7576d635d3bSEd Maste 		printf("%lld", (long long)(line->off + line->boff));
758a4f3f02bSEd Maste 		printsep = true;
7594dc88ebeSGabor Kovesdan 	}
760a4f3f02bSEd Maste 	if (printsep)
7614dc88ebeSGabor Kovesdan 		putchar(sep);
762a4f3f02bSEd Maste }
763a4f3f02bSEd Maste 
764a4f3f02bSEd Maste /*
765*4c9ffb13SKyle Evans  * Prints a matching line according to the command line options.  We need
766*4c9ffb13SKyle Evans  * *last_out to be populated on entry in case this is just a continuation of
767*4c9ffb13SKyle Evans  * matches within the same line.
768*4c9ffb13SKyle Evans  *
769*4c9ffb13SKyle Evans  * Returns true if the line was terminated, false if it was not.
770a4f3f02bSEd Maste  */
771*4c9ffb13SKyle Evans static bool
printline(struct parsec * pc,int sep,size_t * last_out)772*4c9ffb13SKyle Evans printline(struct parsec *pc, int sep, size_t *last_out)
773a4f3f02bSEd Maste {
774*4c9ffb13SKyle Evans 	size_t a = *last_out;
775a4f3f02bSEd Maste 	size_t i, matchidx;
776a4f3f02bSEd Maste 	regmatch_t match;
777*4c9ffb13SKyle Evans 	bool terminated;
778*4c9ffb13SKyle Evans 
779*4c9ffb13SKyle Evans 	/*
780*4c9ffb13SKyle Evans 	 * Nearly all paths below will terminate the line by default, but it is
781*4c9ffb13SKyle Evans 	 * avoided in some circumstances in case we don't have the full context
782*4c9ffb13SKyle Evans 	 * available here.
783*4c9ffb13SKyle Evans 	 */
784*4c9ffb13SKyle Evans 	terminated = true;
785a4f3f02bSEd Maste 
786a4f3f02bSEd Maste 	/* If matchall, everything matches but don't actually print for -o */
787a4f3f02bSEd Maste 	if (oflag && matchall)
788*4c9ffb13SKyle Evans 		return (terminated);
789a4f3f02bSEd Maste 
790a4f3f02bSEd Maste 	matchidx = pc->matchidx;
791a4f3f02bSEd Maste 
7924dc88ebeSGabor Kovesdan 	/* --color and -o */
793*4c9ffb13SKyle Evans 	if ((oflag || color) && (pc->printed > 0 || matchidx > 0)) {
7946d635d3bSEd Maste 		/* Only print metadata once per line if --color */
795*4c9ffb13SKyle Evans 		if (!oflag && pc->printed == 0) {
796a4f3f02bSEd Maste 			printline_metadata(&pc->ln, sep);
797*4c9ffb13SKyle Evans 		}
798a4f3f02bSEd Maste 		for (i = 0; i < matchidx; i++) {
799a4f3f02bSEd Maste 			match = pc->matches[i];
800e06ffa32SEd Maste 			/* Don't output zero length matches */
801a4f3f02bSEd Maste 			if (match.rm_so == match.rm_eo)
802e06ffa32SEd Maste 				continue;
8036d635d3bSEd Maste 			/*
8046d635d3bSEd Maste 			 * Metadata is printed on a per-line basis, so every
8056d635d3bSEd Maste 			 * match gets file metadata with the -o flag.
8066d635d3bSEd Maste 			 */
8076d635d3bSEd Maste 			if (oflag) {
8086d635d3bSEd Maste 				pc->ln.boff = match.rm_so;
8096d635d3bSEd Maste 				printline_metadata(&pc->ln, sep);
810*4c9ffb13SKyle Evans 			} else {
811a4f3f02bSEd Maste 				fwrite(pc->ln.dat + a, match.rm_so - a, 1,
8124dc88ebeSGabor Kovesdan 				    stdout);
813*4c9ffb13SKyle Evans 			}
8144dc88ebeSGabor Kovesdan 			if (color)
815a5ed8685SEd Maste 				fprintf(stdout, "\33[%sm\33[K", color);
816a4f3f02bSEd Maste 			fwrite(pc->ln.dat + match.rm_so,
817a4f3f02bSEd Maste 			    match.rm_eo - match.rm_so, 1, stdout);
8184dc88ebeSGabor Kovesdan 			if (color)
819a5ed8685SEd Maste 				fprintf(stdout, "\33[m\33[K");
820a4f3f02bSEd Maste 			a = match.rm_eo;
8214dc88ebeSGabor Kovesdan 			if (oflag)
8224dc88ebeSGabor Kovesdan 				putchar('\n');
8234dc88ebeSGabor Kovesdan 		}
824*4c9ffb13SKyle Evans 
825*4c9ffb13SKyle Evans 		/*
826*4c9ffb13SKyle Evans 		 * Don't terminate if we reached the match limit; we may have
827*4c9ffb13SKyle Evans 		 * other matches on this line to process.
828*4c9ffb13SKyle Evans 		 */
829*4c9ffb13SKyle Evans 		*last_out = a;
830*4c9ffb13SKyle Evans 		if (!oflag && matchidx != MAX_MATCHES) {
831*4c9ffb13SKyle Evans 			if (pc->ln.len - a > 0) {
832a4f3f02bSEd Maste 				fwrite(pc->ln.dat + a, pc->ln.len - a, 1,
833a4f3f02bSEd Maste 				    stdout);
834*4c9ffb13SKyle Evans 				*last_out = pc->ln.len;
835*4c9ffb13SKyle Evans 			}
8364dc88ebeSGabor Kovesdan 			putchar('\n');
837*4c9ffb13SKyle Evans 		} else if (!oflag) {
838*4c9ffb13SKyle Evans 			/*
839*4c9ffb13SKyle Evans 			 * -o is terminated on every match output, so this
840*4c9ffb13SKyle Evans 			 * branch is only designed to capture MAX_MATCHES in a
841*4c9ffb13SKyle Evans 			 * line which may be a signal to us for a lack of
842*4c9ffb13SKyle Evans 			 * context.  The caller will know more and call us again
843*4c9ffb13SKyle Evans 			 * to terminate if it needs to.
844*4c9ffb13SKyle Evans 			 */
845*4c9ffb13SKyle Evans 			terminated = false;
8464dc88ebeSGabor Kovesdan 		}
847a4f3f02bSEd Maste 	} else
848a4f3f02bSEd Maste 		grep_printline(&pc->ln, sep);
8496d635d3bSEd Maste 	pc->printed++;
850*4c9ffb13SKyle Evans 	return (terminated);
8514dc88ebeSGabor Kovesdan }
852