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