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