xref: /freebsd/usr.bin/look/look.c (revision c4f6a2a9e1b1879b618c436ab4f56ff75c73a0f5)
1 /*-
2  * Copyright (c) 1991, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * David Hitz of Auspex Systems, Inc.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgement:
18  *	This product includes software developed by the University of
19  *	California, Berkeley and its contributors.
20  * 4. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  */
36 
37 #ifndef lint
38 static const char copyright[] =
39 "@(#) Copyright (c) 1991, 1993\n\
40 	The Regents of the University of California.  All rights reserved.\n";
41 #endif /* not lint */
42 
43 #ifndef lint
44 #if 0
45 static char sccsid[] = "@(#)look.c	8.2 (Berkeley) 5/4/95";
46 #endif
47 #endif /* not lint */
48 #include <sys/cdefs.h>
49 __FBSDID("$FreeBSD$");
50 
51 /*
52  * look -- find lines in a sorted list.
53  *
54  * The man page said that TABs and SPACEs participate in -d comparisons.
55  * In fact, they were ignored.  This implements historic practice, not
56  * the manual page.
57  */
58 
59 #include <sys/types.h>
60 #include <sys/mman.h>
61 #include <sys/stat.h>
62 
63 #include <ctype.h>
64 #include <err.h>
65 #include <errno.h>
66 #include <fcntl.h>
67 #include <limits.h>
68 #include <locale.h>
69 #include <stdio.h>
70 #include <stdlib.h>
71 #include <string.h>
72 #include <unistd.h>
73 
74 #include "pathnames.h"
75 
76 static char _path_words[] = _PATH_WORDS;
77 
78 /*
79  * FOLD and DICT convert characters to a normal form for comparison,
80  * according to the user specified flags.
81  *
82  * DICT expects integers because it uses a non-character value to
83  * indicate a character which should not participate in comparisons.
84  */
85 #define	EQUAL		0
86 #define	GREATER		1
87 #define	LESS		(-1)
88 #define NO_COMPARE	(-2)
89 
90 #define FOLD(c) (isupper(c) ? tolower(c) : (unsigned char) (c))
91 #define DICT(c) (isalnum(c) ? (c) & 0xFF /* int */ : NO_COMPARE)
92 
93 int dflag, fflag;
94 
95 char    *binary_search(unsigned char *, unsigned char *, unsigned char *);
96 int      compare(unsigned char *, unsigned char *, unsigned char *);
97 char    *linear_search(unsigned char *, unsigned char *, unsigned char *);
98 int      look(unsigned char *, unsigned char *, unsigned char *);
99 void     print_from(unsigned char *, unsigned char *, unsigned char *);
100 
101 static void usage(void);
102 
103 int
104 main(argc, argv)
105 	int argc;
106 	char *argv[];
107 {
108 	struct stat sb;
109 	int ch, fd, termchar, match;
110 	unsigned char *back, *front, *string, *p;
111 	unsigned const char *file;
112 
113 	(void) setlocale(LC_CTYPE, "");
114 
115 	file = _path_words;
116 	termchar = '\0';
117 	while ((ch = getopt(argc, argv, "dft:")) != -1)
118 		switch(ch) {
119 		case 'd':
120 			dflag = 1;
121 			break;
122 		case 'f':
123 			fflag = 1;
124 			break;
125 		case 't':
126 			termchar = *optarg;
127 			break;
128 		case '?':
129 		default:
130 			usage();
131 		}
132 	argc -= optind;
133 	argv += optind;
134 
135 	if (argc == 0)
136 		usage();
137 	if (argc == 1) 			/* But set -df by default. */
138 		dflag = fflag = 1;
139 	string = *argv++;
140 	if (argc >= 2)
141 		file = *argv++;
142 
143 	if (termchar != '\0' && (p = strchr(string, termchar)) != NULL)
144 		*++p = '\0';
145 	match = 1;
146 
147 	do {
148 		if ((fd = open(file, O_RDONLY, 0)) < 0 || fstat(fd, &sb))
149 			err(2, "%s", file);
150 		if (sb.st_size > SIZE_T_MAX)
151 			errx(2, "%s: %s", file, strerror(EFBIG));
152 		if ((front = mmap(NULL, (size_t)sb.st_size, PROT_READ, MAP_SHARED, fd, (off_t)0)) == MAP_FAILED)
153 			err(2, "%s", file);
154 		back = front + sb.st_size;
155 		match *= (look(string, front, back));
156 		close(fd);
157 	} while (argc-- > 2 && (file = *argv++));
158 
159 	exit(match);
160 }
161 
162 int
163 look(string, front, back)
164 	unsigned char *string, *front, *back;
165 {
166 	register int ch;
167 	register unsigned char *readp, *writep;
168 
169 	/* Reformat string string to avoid doing it multiple times later. */
170 	for (readp = writep = string; (ch = *readp++);) {
171 		if (fflag)
172 			ch = FOLD(ch);
173 		if (dflag)
174 			ch = DICT(ch);
175 		if (ch != NO_COMPARE)
176 			*(writep++) = ch;
177 	}
178 	*writep = '\0';
179 
180 	front = binary_search(string, front, back);
181 	front = linear_search(string, front, back);
182 
183 	if (front)
184 		print_from(string, front, back);
185 	return (front ? 0 : 1);
186 }
187 
188 
189 /*
190  * Binary search for "string" in memory between "front" and "back".
191  *
192  * This routine is expected to return a pointer to the start of a line at
193  * *or before* the first word matching "string".  Relaxing the constraint
194  * this way simplifies the algorithm.
195  *
196  * Invariants:
197  * 	front points to the beginning of a line at or before the first
198  *	matching string.
199  *
200  * 	back points to the beginning of a line at or after the first
201  *	matching line.
202  *
203  * Base of the Invariants.
204  * 	front = NULL;
205  *	back = EOF;
206  *
207  * Advancing the Invariants:
208  *
209  * 	p = first newline after halfway point from front to back.
210  *
211  * 	If the string at "p" is not greater than the string to match,
212  *	p is the new front.  Otherwise it is the new back.
213  *
214  * Termination:
215  *
216  * 	The definition of the routine allows it return at any point,
217  *	since front is always at or before the line to print.
218  *
219  * 	In fact, it returns when the chosen "p" equals "back".  This
220  *	implies that there exists a string is least half as long as
221  *	(back - front), which in turn implies that a linear search will
222  *	be no more expensive than the cost of simply printing a string or two.
223  *
224  * 	Trying to continue with binary search at this point would be
225  *	more trouble than it's worth.
226  */
227 #define	SKIP_PAST_NEWLINE(p, back) \
228 	while (p < back && *p++ != '\n');
229 
230 char *
231 binary_search(string, front, back)
232 	register unsigned char *string, *front, *back;
233 {
234 	register unsigned char *p;
235 
236 	p = front + (back - front) / 2;
237 	SKIP_PAST_NEWLINE(p, back);
238 
239 	/*
240 	 * If the file changes underneath us, make sure we don't
241 	 * infinitely loop.
242 	 */
243 	while (p < back && back > front) {
244 		if (compare(string, p, back) == GREATER)
245 			front = p;
246 		else
247 			back = p;
248 		p = front + (back - front) / 2;
249 		SKIP_PAST_NEWLINE(p, back);
250 	}
251 	return (front);
252 }
253 
254 /*
255  * Find the first line that starts with string, linearly searching from front
256  * to back.
257  *
258  * Return NULL for no such line.
259  *
260  * This routine assumes:
261  *
262  * 	o front points at the first character in a line.
263  *	o front is before or at the first line to be printed.
264  */
265 char *
266 linear_search(string, front, back)
267 	unsigned char *string, *front, *back;
268 {
269 	while (front < back) {
270 		switch (compare(string, front, back)) {
271 		case EQUAL:		/* Found it. */
272 			return (front);
273 			break;
274 		case LESS:		/* No such string. */
275 			return (NULL);
276 			break;
277 		case GREATER:		/* Keep going. */
278 			break;
279 		}
280 		SKIP_PAST_NEWLINE(front, back);
281 	}
282 	return (NULL);
283 }
284 
285 /*
286  * Print as many lines as match string, starting at front.
287  */
288 void
289 print_from(string, front, back)
290 	register unsigned char *string, *front, *back;
291 {
292 	for (; front < back && compare(string, front, back) == EQUAL; ++front) {
293 		for (; front < back && *front != '\n'; ++front)
294 			if (putchar(*front) == EOF)
295 				err(2, "stdout");
296 		if (putchar('\n') == EOF)
297 			err(2, "stdout");
298 	}
299 }
300 
301 /*
302  * Return LESS, GREATER, or EQUAL depending on how the string1 compares with
303  * string2 (s1 ??? s2).
304  *
305  * 	o Matches up to len(s1) are EQUAL.
306  *	o Matches up to len(s2) are GREATER.
307  *
308  * Compare understands about the -f and -d flags, and treats comparisons
309  * appropriately.
310  *
311  * The string "s1" is null terminated.  The string s2 is '\n' terminated (or
312  * "back" terminated).
313  */
314 int
315 compare(s1, s2, back)
316 	register unsigned char *s1, *s2, *back;
317 {
318 	register int ch;
319 
320 	for (; *s1 && s2 < back && *s2 != '\n'; ++s1, ++s2) {
321 		ch = *s2;
322 		if (fflag)
323 			ch = FOLD(ch);
324 		if (dflag)
325 			ch = DICT(ch);
326 
327 		if (ch == NO_COMPARE) {
328 			++s2;		/* Ignore character in comparison. */
329 			continue;
330 		}
331 		if (*s1 != ch)
332 			return (*s1 < ch ? LESS : GREATER);
333 	}
334 	return (*s1 ? GREATER : EQUAL);
335 }
336 
337 static void
338 usage()
339 {
340 	(void)fprintf(stderr, "usage: look [-df] [-t char] string [file ...]\n");
341 	exit(2);
342 }
343