Home | History | Annotate | Line # | Download | only in strfile
strfile.c revision 1.38.18.1
      1 /*	$NetBSD: strfile.c,v 1.38.18.1 2020/04/30 16:21:14 martin Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1989, 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  * Ken Arnold.
      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 #if HAVE_NBTOOL_CONFIG_H
     36 #include "nbtool_config.h"
     37 #endif
     38 
     39 #ifdef __NetBSD__
     40 #include <sys/cdefs.h>
     41 #ifndef lint
     42 __COPYRIGHT("@(#) Copyright (c) 1989, 1993\
     43  The Regents of the University of California.  All rights reserved.");
     44 #endif /* not lint */
     45 
     46 #ifndef lint
     47 #if 0
     48 static char sccsid[] = "@(#)strfile.c	8.1 (Berkeley) 5/31/93";
     49 #else
     50 __RCSID("$NetBSD: strfile.c,v 1.38.18.1 2020/04/30 16:21:14 martin Exp $");
     51 #endif
     52 #endif /* not lint */
     53 #endif /* __NetBSD__ */
     54 
     55 #include <sys/types.h>
     56 #include <sys/param.h>
     57 #include <ctype.h>
     58 #include <stdio.h>
     59 #include <stdlib.h>
     60 #include <string.h>
     61 #include <time.h>
     62 #include <unistd.h>
     63 #include <inttypes.h>
     64 #include <err.h>
     65 
     66 #include "strfile.h"
     67 
     68 #ifndef MAXPATHLEN
     69 #define	MAXPATHLEN	1024
     70 #endif	/* MAXPATHLEN */
     71 
     72 /*
     73  *	This program takes a file composed of strings separated by
     74  * lines starting with two consecutive delimiting character (default
     75  * character is '%') and creates another file which consists of a table
     76  * describing the file (structure from "strfile.h"), a table of seek
     77  * pointers to the start of the strings, and the strings, each terminated
     78  * by a null byte.  Usage:
     79  *
     80  *	% strfile [-iorsx] [ -cC ] sourcefile [ datafile ]
     81  *
     82  *	c - Change delimiting character from '%' to 'C'
     83  *	s - Silent.  Give no summary of data processed at the end of
     84  *	    the run.
     85  *	o - order the strings in alphabetic order
     86  *	i - if ordering, ignore case
     87  *	r - randomize the order of the strings
     88  *	x - set rotated bit
     89  *
     90  *		Ken Arnold	Sept. 7, 1978 --
     91  *
     92  *	Added ordering options.
     93  */
     94 
     95 # define	STORING_PTRS	(Oflag || Rflag)
     96 # define	CHUNKSIZE	512
     97 
     98 # define	ALLOC(ptr,sz)	do { \
     99 			if (ptr == NULL) \
    100 				ptr = malloc(CHUNKSIZE * sizeof *ptr); \
    101 			else if (((sz) + 1) % CHUNKSIZE == 0) \
    102 				ptr = realloc(ptr, ((sz) + CHUNKSIZE) * sizeof *ptr); \
    103 			if (ptr == NULL) \
    104 				err(1, "out of space"); \
    105 		} while (0)
    106 
    107 typedef struct {
    108 	char	first;
    109 	off_t	pos;
    110 } STR;
    111 
    112 static char *Infile = NULL;		/* input file name */
    113 static char Outfile[MAXPATHLEN] = "";	/* output file name */
    114 static char Delimch = '%';		/* delimiting character */
    115 
    116 static int Sflag	= 0;		/* silent run flag */
    117 static int Oflag	= 0;		/* ordering flag */
    118 static int Iflag	= 0;		/* ignore case flag */
    119 static int Rflag	= 0;		/* randomize order flag */
    120 static int Xflag	= 0;		/* set rotated bit */
    121 static long Num_pts	= 0;		/* number of pointers/strings */
    122 
    123 static off_t *Seekpts;
    124 
    125 static FILE *Sort_1, *Sort_2;		/* pointers for sorting */
    126 
    127 static STRFILE Tbl;			/* statistics table */
    128 
    129 static STR *Firstch;			/* first chars of each string */
    130 
    131 
    132 static uint32_t h2nl(uint32_t h);
    133 static void getargs(int argc, char **argv);
    134 static void usage(void) __dead;
    135 static void add_offset(FILE *fp, off_t off);
    136 static void do_order(void);
    137 static int cmp_str(const void *vp1, const void *vp2);
    138 static void randomize(void);
    139 static void fwrite_be_offt(off_t off, FILE *f);
    140 
    141 
    142 /*
    143  * main:
    144  *	Drive the sucker.  There are two main modes -- either we store
    145  *	the seek pointers, if the table is to be sorted or randomized,
    146  *	or we write the pointer directly to the file, if we are to stay
    147  *	in file order.  If the former, we allocate and re-allocate in
    148  *	CHUNKSIZE blocks; if the latter, we just write each pointer,
    149  *	and then seek back to the beginning to write in the table.
    150  */
    151 int
    152 main(int ac, char **av)
    153 {
    154 	char		*sp, dc;
    155 	FILE		*inf, *outf;
    156 	off_t		last_off, length, pos;
    157 	int		first;
    158 	char		*nsp;
    159 	STR		*fp;
    160 	static char	string[257];
    161 	long		i;
    162 
    163 	/* sanity test */
    164 	if (sizeof(uint32_t) != 4)
    165 		errx(1, "sizeof(uint32_t) != 4");
    166 
    167 	getargs(ac, av);		/* evalute arguments */
    168 	dc = Delimch;
    169 	if ((inf = fopen(Infile, "r")) == NULL)
    170 		err(1, "open `%s'", Infile);
    171 
    172 	if ((outf = fopen(Outfile, "w")) == NULL)
    173 		err(1, "open `%s'", Outfile);
    174 	if (!STORING_PTRS)
    175 		(void) fseek(outf, sizeof Tbl, SEEK_SET);
    176 
    177 	/*
    178 	 * Write the strings onto the file
    179 	 */
    180 
    181 	Tbl.str_longlen = 0;
    182 	Tbl.str_shortlen = (unsigned int) 0x7fffffff;
    183 	Tbl.str_delim = dc;
    184 	Tbl.str_version = VERSION;
    185 	first = Oflag;
    186 	add_offset(outf, ftell(inf));
    187 	last_off = 0;
    188 	do {
    189 		sp = fgets(string, 256, inf);
    190 		if (sp == NULL || (sp[0] == dc && sp[1] == '\n')) {
    191 			pos = ftell(inf);
    192 			length = pos - last_off - (sp ? strlen(sp) : 0);
    193 			last_off = pos;
    194 			if (!length)
    195 				continue;
    196 			add_offset(outf, pos);
    197 			if ((off_t)Tbl.str_longlen < length)
    198 				Tbl.str_longlen = length;
    199 			if ((off_t)Tbl.str_shortlen > length)
    200 				Tbl.str_shortlen = length;
    201 			first = Oflag;
    202 		}
    203 		else if (first) {
    204 			for (nsp = sp; !isalnum((unsigned char)*nsp); nsp++)
    205 				continue;
    206 			ALLOC(Firstch, Num_pts);
    207 			fp = &Firstch[Num_pts - 1];
    208 			if (Iflag && isupper((unsigned char)*nsp))
    209 				fp->first = tolower((unsigned char)*nsp);
    210 			else
    211 				fp->first = *nsp;
    212 			fp->pos = Seekpts[Num_pts - 1];
    213 			first = 0;
    214 		}
    215 	} while (sp != NULL);
    216 
    217 	/*
    218 	 * write the tables in
    219 	 */
    220 
    221 	(void) fclose(inf);
    222 
    223 	if (Oflag)
    224 		do_order();
    225 	else if (Rflag)
    226 		randomize();
    227 
    228 	if (Xflag)
    229 		Tbl.str_flags |= STR_ROTATED;
    230 
    231 	if (!Sflag) {
    232 		printf("\"%s\" created\n", Outfile);
    233 		if (Num_pts == 2)
    234 			puts("There was 1 string");
    235 		else
    236 			printf("There were %d strings\n", (int)(Num_pts - 1));
    237 		printf("Longest string: %lu byte%s\n", (unsigned long)Tbl.str_longlen,
    238 		       Tbl.str_longlen == 1 ? "" : "s");
    239 		printf("Shortest string: %lu byte%s\n", (unsigned long)Tbl.str_shortlen,
    240 		       Tbl.str_shortlen == 1 ? "" : "s");
    241 	}
    242 
    243 	(void) fseek(outf, (off_t) 0, SEEK_SET);
    244 	Tbl.str_version = h2nl(Tbl.str_version);
    245 	Tbl.str_numstr = h2nl(Num_pts - 1);
    246 	Tbl.str_longlen = h2nl(Tbl.str_longlen);
    247 	Tbl.str_shortlen = h2nl(Tbl.str_shortlen);
    248 	Tbl.str_flags = h2nl(Tbl.str_flags);
    249 	(void) fwrite((char *) &Tbl, sizeof Tbl, 1, outf);
    250 	if (STORING_PTRS) {
    251 		for (i = 0; i < Num_pts; i++)
    252 			fwrite_be_offt(Seekpts[i], outf);
    253 	}
    254 	fflush(outf);
    255 	if (ferror(outf))
    256 		err(1, "fwrite %s", Outfile);
    257 	(void) fclose(outf);
    258 	exit(0);
    259 }
    260 
    261 /*
    262  *	This routine evaluates arguments from the command line
    263  */
    264 static void
    265 getargs(int argc, char **argv)
    266 {
    267 	int	ch;
    268 	extern	int optind;
    269 	extern	char *optarg;
    270 	size_t	len;
    271 
    272 	while ((ch = getopt(argc, argv, "c:iorsx")) != -1)
    273 		switch(ch) {
    274 		case 'c':			/* new delimiting char */
    275 			Delimch = *optarg;
    276 			if (!isascii(Delimch)) {
    277 				printf("bad delimiting character: '\\%o\n'",
    278 				       Delimch);
    279 			}
    280 			break;
    281 		case 'i':			/* ignore case in ordering */
    282 			Iflag++;
    283 			break;
    284 		case 'o':			/* order strings */
    285 			Oflag++;
    286 			break;
    287 		case 'r':			/* randomize pointers */
    288 			Rflag++;
    289 			break;
    290 		case 's':			/* silent */
    291 			Sflag++;
    292 			break;
    293 		case 'x':			/* set the rotated bit */
    294 			Xflag++;
    295 			break;
    296 		case '?':
    297 		default:
    298 			usage();
    299 		}
    300 	argv += optind;
    301 
    302 	if (*argv) {
    303 		Infile = *argv;
    304 		if (*++argv) {
    305 			len = strlen(*argv);
    306 			if (len >= sizeof(Outfile)) {
    307 				puts("Bad output filename");
    308 				usage();
    309 			}
    310 			(void) memcpy(Outfile, *argv, len + 1);
    311 		}
    312 	}
    313 	if (!Infile) {
    314 		puts("No input file name");
    315 		usage();
    316 	}
    317 	if (*Outfile == '\0') {
    318 		len = strlen(Infile) + sizeof(".dat");
    319 		if (len > sizeof(Outfile)) {
    320 			puts("Bad input filename");
    321 			usage();
    322 		}
    323 		(void) strcpy(Outfile, Infile);
    324 		(void) strcat(Outfile, ".dat");
    325 	}
    326 }
    327 
    328 static void
    329 usage(void)
    330 {
    331 	(void) fprintf(stderr,
    332 	    "Usage: %s [-iorsx] [-c char] sourcefile [datafile]\n",
    333 	    getprogname());
    334 	exit(1);
    335 }
    336 
    337 /*
    338  * add_offset:
    339  *	Add an offset to the list, or write it out, as appropriate.
    340  */
    341 static void
    342 add_offset(FILE *fp, off_t off)
    343 {
    344 
    345 	if (!STORING_PTRS) {
    346 		fwrite_be_offt(off, fp);
    347 	} else {
    348 		ALLOC(Seekpts, Num_pts + 1);
    349 		Seekpts[Num_pts] = off;
    350 	}
    351 	Num_pts++;
    352 }
    353 
    354 /*
    355  * do_order:
    356  *	Order the strings alphabetically (possibly ignoring case).
    357  */
    358 static void
    359 do_order(void)
    360 {
    361 	int	i;
    362 	off_t	*lp;
    363 	STR	*fp;
    364 
    365 	Sort_1 = fopen(Infile, "r");
    366 	Sort_2 = fopen(Infile, "r");
    367 	qsort((char *) Firstch, (int) Tbl.str_numstr, sizeof *Firstch, cmp_str);
    368 	i = Tbl.str_numstr;
    369 	lp = Seekpts;
    370 	fp = Firstch;
    371 	while (i--)
    372 		*lp++ = fp++->pos;
    373 	(void) fclose(Sort_1);
    374 	(void) fclose(Sort_2);
    375 	Tbl.str_flags |= STR_ORDERED;
    376 }
    377 
    378 static int
    379 cmp_str(const void *vp1, const void *vp2)
    380 {
    381 	const STR	*p1, *p2;
    382 	int	c1, c2;
    383 	int	n1, n2;
    384 
    385 	p1 = (const STR *)vp1;
    386 	p2 = (const STR *)vp2;
    387 
    388 # define	SET_N(nf,ch)	(nf = (ch == '\n'))
    389 # define	IS_END(ch,nf)	(ch == Delimch && nf)
    390 
    391 	c1 = p1->first;
    392 	c2 = p2->first;
    393 	if (c1 != c2)
    394 		return c1 - c2;
    395 
    396 	(void) fseek(Sort_1, p1->pos, SEEK_SET);
    397 	(void) fseek(Sort_2, p2->pos, SEEK_SET);
    398 
    399 	n1 = 0;
    400 	n2 = 0;
    401 	while (!isalnum(c1 = getc(Sort_1)) && c1 != '\0')
    402 		SET_N(n1, c1);
    403 	while (!isalnum(c2 = getc(Sort_2)) && c2 != '\0')
    404 		SET_N(n2, c2);
    405 
    406 	while (!IS_END(c1, n1) && !IS_END(c2, n2)) {
    407 		if (Iflag) {
    408 			if (isupper(c1))
    409 				c1 = tolower(c1);
    410 			if (isupper(c2))
    411 				c2 = tolower(c2);
    412 		}
    413 		if (c1 != c2)
    414 			return c1 - c2;
    415 		SET_N(n1, c1);
    416 		SET_N(n2, c2);
    417 		c1 = getc(Sort_1);
    418 		c2 = getc(Sort_2);
    419 	}
    420 	if (IS_END(c1, n1))
    421 		c1 = 0;
    422 	if (IS_END(c2, n2))
    423 		c2 = 0;
    424 	return c1 - c2;
    425 }
    426 
    427 /*
    428  * randomize:
    429  *	Randomize the order of the string table.  We must be careful
    430  *	not to randomize across delimiter boundaries.  All
    431  *	randomization is done within each block.
    432  */
    433 static void
    434 randomize(void)
    435 {
    436 	int	cnt, i;
    437 	off_t	tmp;
    438 	off_t	*sp;
    439 
    440 	srandom((int)(time(NULL) + getpid()));
    441 
    442 	Tbl.str_flags |= STR_RANDOM;
    443 	cnt = Tbl.str_numstr;
    444 
    445 	/*
    446 	 * move things around randomly
    447 	 */
    448 
    449 	for (sp = Seekpts; cnt > 0; cnt--, sp++) {
    450 		i = random() % cnt;
    451 		tmp = sp[0];
    452 		sp[0] = sp[i];
    453 		sp[i] = tmp;
    454 	}
    455 }
    456 
    457 /*
    458  * fwrite_be_offt:
    459  *	Write out the off paramater as a 64 bit big endian number
    460  */
    461 
    462 static void
    463 fwrite_be_offt(off_t off, FILE *f)
    464 {
    465 	int		i;
    466 	unsigned char	c[8];
    467 
    468 	for (i = 7; i >= 0; i--) {
    469 		c[i] = off & 0xff;
    470 		off >>= 8;
    471 	}
    472 	fwrite(c, sizeof(c), 1, f);
    473 }
    474 
    475 static uint32_t
    476 h2nl(uint32_t h)
    477 {
    478         unsigned char c[4];
    479         uint32_t rv;
    480 
    481         c[0] = (h >> 24) & 0xff;
    482         c[1] = (h >> 16) & 0xff;
    483         c[2] = (h >>  8) & 0xff;
    484         c[3] = (h >>  0) & 0xff;
    485         memcpy(&rv, c, sizeof rv);
    486 
    487         return (rv);
    488 }
    489