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