Add the DragonFly cvs id and perform general cleanups on cvs/rcs/sccs ids. Most
[dragonfly.git] / usr.bin / look / look.c
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  * @(#) Copyright (c) 1991, 1993 The Regents of the University of California.  All rights reserved.
37  * @(#)look.c   8.2 (Berkeley) 5/4/95
38  * $FreeBSD: src/usr.bin/look/look.c,v 1.11 1999/08/28 01:03:14 peter Exp $
39  * $DragonFly: src/usr.bin/look/look.c,v 1.2 2003/06/17 04:29:28 dillon Exp $
40  */
41
42 /*
43  * look -- find lines in a sorted list.
44  *
45  * The man page said that TABs and SPACEs participate in -d comparisons.
46  * In fact, they were ignored.  This implements historic practice, not
47  * the manual page.
48  */
49
50 #include <sys/types.h>
51 #include <sys/mman.h>
52 #include <sys/stat.h>
53
54 #include <ctype.h>
55 #include <err.h>
56 #include <errno.h>
57 #include <fcntl.h>
58 #include <limits.h>
59 #include <locale.h>
60 #include <stdio.h>
61 #include <stdlib.h>
62 #include <string.h>
63 #include <unistd.h>
64
65 #include "pathnames.h"
66
67 /*
68  * FOLD and DICT convert characters to a normal form for comparison,
69  * according to the user specified flags.
70  *
71  * DICT expects integers because it uses a non-character value to
72  * indicate a character which should not participate in comparisons.
73  */
74 #define EQUAL           0
75 #define GREATER         1
76 #define LESS            (-1)
77 #define NO_COMPARE      (-2)
78
79 #define FOLD(c) (isupper(c) ? tolower(c) : (unsigned char) (c))
80 #define DICT(c) (isalnum(c) ? (c) & 0xFF /* int */ : NO_COMPARE)
81
82 int dflag, fflag;
83
84 char    *binary_search __P((unsigned char *, unsigned char *, unsigned char *));
85 int      compare __P((unsigned char *, unsigned char *, unsigned char *));
86 char    *linear_search __P((unsigned char *, unsigned char *, unsigned char *));
87 int      look __P((unsigned char *, unsigned char *, unsigned char *));
88 void     print_from __P((unsigned char *, unsigned char *, unsigned char *));
89
90 static void usage __P((void));
91
92 int
93 main(argc, argv)
94         int argc;
95         char *argv[];
96 {
97         struct stat sb;
98         int ch, fd, termchar, match;
99         unsigned char *back, *file, *front, *string, *p;
100
101         (void) setlocale(LC_CTYPE, "");
102
103         file = _PATH_WORDS;
104         termchar = '\0';
105         while ((ch = getopt(argc, argv, "dft:")) != -1)
106                 switch(ch) {
107                 case 'd':
108                         dflag = 1;
109                         break;
110                 case 'f':
111                         fflag = 1;
112                         break;
113                 case 't':
114                         termchar = *optarg;
115                         break;
116                 case '?':
117                 default:
118                         usage();
119                 }
120         argc -= optind;
121         argv += optind;
122
123         if (argc == 0)
124                 usage();
125         if (argc == 1)                  /* But set -df by default. */
126                 dflag = fflag = 1;
127         string = *argv++;
128         if (argc >= 2)
129                 file = *argv++;
130
131         if (termchar != '\0' && (p = strchr(string, termchar)) != NULL)
132                 *++p = '\0';
133         match = 1;
134
135         do {
136                 if ((fd = open(file, O_RDONLY, 0)) < 0 || fstat(fd, &sb))
137                         err(2, "%s", file);
138                 if (sb.st_size > SIZE_T_MAX)
139                         errx(2, "%s: %s", file, strerror(EFBIG));
140                 if ((front = mmap(NULL, (size_t)sb.st_size, PROT_READ, MAP_SHARED, fd, (off_t)0)) == MAP_FAILED)
141                         err(2, "%s", file);
142                 back = front + sb.st_size;
143                 match *= (look(string, front, back));
144                 close(fd);
145         } while (argc-- > 2 && (file = *argv++));
146
147         exit(match);
148 }
149
150 int
151 look(string, front, back)
152         unsigned char *string, *front, *back;
153 {
154         register int ch;
155         register unsigned char *readp, *writep;
156
157         /* Reformat string string to avoid doing it multiple times later. */
158         for (readp = writep = string; ch = *readp++;) {
159                 if (fflag)
160                         ch = FOLD(ch);
161                 if (dflag)
162                         ch = DICT(ch);
163                 if (ch != NO_COMPARE)
164                         *(writep++) = ch;
165         }
166         *writep = '\0';
167
168         front = binary_search(string, front, back);
169         front = linear_search(string, front, back);
170
171         if (front)
172                 print_from(string, front, back);
173         return (front ? 0 : 1);
174 }
175
176
177 /*
178  * Binary search for "string" in memory between "front" and "back".
179  *
180  * This routine is expected to return a pointer to the start of a line at
181  * *or before* the first word matching "string".  Relaxing the constraint
182  * this way simplifies the algorithm.
183  *
184  * Invariants:
185  *      front points to the beginning of a line at or before the first
186  *      matching string.
187  *
188  *      back points to the beginning of a line at or after the first
189  *      matching line.
190  *
191  * Base of the Invariants.
192  *      front = NULL;
193  *      back = EOF;
194  *
195  * Advancing the Invariants:
196  *
197  *      p = first newline after halfway point from front to back.
198  *
199  *      If the string at "p" is not greater than the string to match,
200  *      p is the new front.  Otherwise it is the new back.
201  *
202  * Termination:
203  *
204  *      The definition of the routine allows it return at any point,
205  *      since front is always at or before the line to print.
206  *
207  *      In fact, it returns when the chosen "p" equals "back".  This
208  *      implies that there exists a string is least half as long as
209  *      (back - front), which in turn implies that a linear search will
210  *      be no more expensive than the cost of simply printing a string or two.
211  *
212  *      Trying to continue with binary search at this point would be
213  *      more trouble than it's worth.
214  */
215 #define SKIP_PAST_NEWLINE(p, back) \
216         while (p < back && *p++ != '\n');
217
218 char *
219 binary_search(string, front, back)
220         register unsigned char *string, *front, *back;
221 {
222         register unsigned char *p;
223
224         p = front + (back - front) / 2;
225         SKIP_PAST_NEWLINE(p, back);
226
227         /*
228          * If the file changes underneath us, make sure we don't
229          * infinitely loop.
230          */
231         while (p < back && back > front) {
232                 if (compare(string, p, back) == GREATER)
233                         front = p;
234                 else
235                         back = p;
236                 p = front + (back - front) / 2;
237                 SKIP_PAST_NEWLINE(p, back);
238         }
239         return (front);
240 }
241
242 /*
243  * Find the first line that starts with string, linearly searching from front
244  * to back.
245  *
246  * Return NULL for no such line.
247  *
248  * This routine assumes:
249  *
250  *      o front points at the first character in a line.
251  *      o front is before or at the first line to be printed.
252  */
253 char *
254 linear_search(string, front, back)
255         unsigned char *string, *front, *back;
256 {
257         while (front < back) {
258                 switch (compare(string, front, back)) {
259                 case EQUAL:             /* Found it. */
260                         return (front);
261                         break;
262                 case LESS:              /* No such string. */
263                         return (NULL);
264                         break;
265                 case GREATER:           /* Keep going. */
266                         break;
267                 }
268                 SKIP_PAST_NEWLINE(front, back);
269         }
270         return (NULL);
271 }
272
273 /*
274  * Print as many lines as match string, starting at front.
275  */
276 void
277 print_from(string, front, back)
278         register unsigned char *string, *front, *back;
279 {
280         for (; front < back && compare(string, front, back) == EQUAL; ++front) {
281                 for (; front < back && *front != '\n'; ++front)
282                         if (putchar(*front) == EOF)
283                                 err(2, "stdout");
284                 if (putchar('\n') == EOF)
285                         err(2, "stdout");
286         }
287 }
288
289 /*
290  * Return LESS, GREATER, or EQUAL depending on how the string1 compares with
291  * string2 (s1 ??? s2).
292  *
293  *      o Matches up to len(s1) are EQUAL.
294  *      o Matches up to len(s2) are GREATER.
295  *
296  * Compare understands about the -f and -d flags, and treats comparisons
297  * appropriately.
298  *
299  * The string "s1" is null terminated.  The string s2 is '\n' terminated (or
300  * "back" terminated).
301  */
302 int
303 compare(s1, s2, back)
304         register unsigned char *s1, *s2, *back;
305 {
306         register int ch;
307
308         for (; *s1 && s2 < back && *s2 != '\n'; ++s1, ++s2) {
309                 ch = *s2;
310                 if (fflag)
311                         ch = FOLD(ch);
312                 if (dflag)
313                         ch = DICT(ch);
314
315                 if (ch == NO_COMPARE) {
316                         ++s2;           /* Ignore character in comparison. */
317                         continue;
318                 }
319                 if (*s1 != ch)
320                         return (*s1 < ch ? LESS : GREATER);
321         }
322         return (*s1 ? GREATER : EQUAL);
323 }
324
325 static void
326 usage()
327 {
328         (void)fprintf(stderr, "usage: look [-df] [-t char] string [file ...]\n");
329         exit(2);
330 }