1/*
2 * Copyright (c) 1994 University of Maryland
3 * All Rights Reserved.
4 *
5 * Permission to use, copy, modify, distribute, and sell this software and its
6 * documentation for any purpose is hereby granted without fee, provided that
7 * the above copyright notice appear in all copies and that both that
8 * copyright notice and this permission notice appear in supporting
9 * documentation, and that the name of U.M. not be used in advertising or
10 * publicity pertaining to distribution of the software without specific,
11 * written prior permission.  U.M. makes no representations about the
12 * suitability of this software for any purpose.  It is provided "as is"
13 * without express or implied warranty.
14 *
15 * U.M. DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL U.M.
17 * BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
18 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
19 * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
20 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
21 *
22 * Author: James da Silva, Systems Design and Analysis Group
23 *			   Computer Science Department
24 *			   University of Maryland at College Park
25 */
26/*
27 * ========================================================================
28 * crunchgen.c
29 *
30 * Generates a Makefile and main C file for a crunched executable,
31 * from specs given in a .conf file.
32 */
33
34#include <sys/cdefs.h>
35__FBSDID("$FreeBSD$");
36
37#include <sys/param.h>
38#include <sys/stat.h>
39
40#include <ctype.h>
41#include <err.h>
42#include <fcntl.h>
43#include <paths.h>
44#include <stdbool.h>
45#include <stdio.h>
46#include <stdlib.h>
47#include <string.h>
48#include <sysexits.h>
49#include <unistd.h>
50
51#define CRUNCH_VERSION	"0.2"
52
53#define MAXLINELEN	16384
54#define MAXFIELDS 	 2048
55
56
57/* internal representation of conf file: */
58
59/* simple lists of strings suffice for most parms */
60
61typedef struct strlst {
62	struct strlst *next;
63	char *str;
64} strlst_t;
65
66/* progs have structure, each field can be set with "special" or calculated */
67
68typedef struct prog {
69	struct prog *next;	/* link field */
70	char *name;		/* program name */
71	char *ident;		/* C identifier for the program name */
72	char *srcdir;
73	char *realsrcdir;
74	char *objdir;
75	char *objvar;		/* Makefile variable to replace OBJS */
76	strlst_t *objs, *objpaths;
77	strlst_t *buildopts;
78	strlst_t *keeplist;
79	strlst_t *links;
80	strlst_t *libs;
81	strlst_t *libs_so;
82	int goterror;
83} prog_t;
84
85
86/* global state */
87
88strlst_t *buildopts = NULL;
89strlst_t *srcdirs   = NULL;
90strlst_t *libs      = NULL;
91strlst_t *libs_so   = NULL;
92prog_t   *progs     = NULL;
93
94char confname[MAXPATHLEN], infilename[MAXPATHLEN];
95char outmkname[MAXPATHLEN], outcfname[MAXPATHLEN], execfname[MAXPATHLEN];
96char tempfname[MAXPATHLEN], cachename[MAXPATHLEN], curfilename[MAXPATHLEN];
97bool tempfname_initialized = false;
98char outhdrname[MAXPATHLEN] ;	/* user-supplied header for *.mk */
99char *objprefix;		/* where are the objects ? */
100char *path_make;
101int linenum = -1;
102int goterror = 0;
103
104int verbose, readcache;		/* options */
105int reading_cache;
106int makeobj = 0;		/* add 'make obj' rules to the makefile */
107
108int list_mode;
109
110/* general library routines */
111
112void status(const char *str);
113void out_of_memory(void);
114void add_string(strlst_t **listp, char *str);
115int is_dir(const char *pathname);
116int is_nonempty_file(const char *pathname);
117int subtract_strlst(strlst_t **lista, strlst_t **listb);
118int in_list(strlst_t **listp, char *str);
119
120/* helper routines for main() */
121
122void usage(void);
123void parse_conf_file(void);
124void gen_outputs(void);
125
126extern char *crunched_skel[];
127
128
129int
130main(int argc, char **argv)
131{
132	char *p;
133	int optc;
134
135	verbose = 1;
136	readcache = 1;
137	*outmkname = *outcfname = *execfname = '\0';
138
139	path_make = getenv("MAKE");
140	if (path_make == NULL || *path_make == '\0')
141		path_make = "make";
142
143	p = getenv("MAKEOBJDIRPREFIX");
144	if (p == NULL || *p == '\0')
145		objprefix = "/usr/obj"; /* default */
146	else
147		if ((objprefix = strdup(p)) == NULL)
148			out_of_memory();
149
150	while((optc = getopt(argc, argv, "lh:m:c:e:p:foq")) != -1) {
151		switch(optc) {
152		case 'f':
153			readcache = 0;
154			break;
155		case 'o':
156			makeobj = 1;
157			break;
158		case 'q':
159			verbose = 0;
160			break;
161
162		case 'm':
163			strlcpy(outmkname, optarg, sizeof(outmkname));
164			break;
165		case 'p':
166			if ((objprefix = strdup(optarg)) == NULL)
167				out_of_memory();
168			break;
169
170		case 'h':
171			strlcpy(outhdrname, optarg, sizeof(outhdrname));
172			break;
173		case 'c':
174			strlcpy(outcfname, optarg, sizeof(outcfname));
175			break;
176		case 'e':
177			strlcpy(execfname, optarg, sizeof(execfname));
178			break;
179
180		case 'l':
181			list_mode++;
182			verbose = 0;
183			break;
184
185		case '?':
186		default:
187			usage();
188		}
189	}
190
191	argc -= optind;
192	argv += optind;
193
194	if (argc != 1)
195		usage();
196
197	/*
198	 * generate filenames
199	 */
200
201	strlcpy(infilename, argv[0], sizeof(infilename));
202
203	/* confname = `basename infilename .conf` */
204
205	if ((p=strrchr(infilename, '/')) != NULL)
206		strlcpy(confname, p + 1, sizeof(confname));
207	else
208		strlcpy(confname, infilename, sizeof(confname));
209
210	if ((p=strrchr(confname, '.')) != NULL && !strcmp(p, ".conf"))
211		*p = '\0';
212
213	if (!*outmkname)
214		snprintf(outmkname, sizeof(outmkname), "%s.mk", confname);
215	if (!*outcfname)
216		snprintf(outcfname, sizeof(outcfname), "%s.c", confname);
217	if (!*execfname)
218		snprintf(execfname, sizeof(execfname), "%s", confname);
219
220	snprintf(cachename, sizeof(cachename), "%s.cache", confname);
221	snprintf(tempfname, sizeof(tempfname), "%s/crunchgen_%sXXXXXX",
222	getenv("TMPDIR") ? getenv("TMPDIR") : _PATH_TMP, confname);
223	tempfname_initialized = false;
224
225	parse_conf_file();
226	if (list_mode)
227		exit(goterror);
228
229	gen_outputs();
230
231	exit(goterror);
232}
233
234
235void
236usage(void)
237{
238	fprintf(stderr, "%s%s\n\t%s%s\n", "usage: crunchgen [-foq] ",
239	    "[-h <makefile-header-name>] [-m <makefile>]",
240	    "[-p <obj-prefix>] [-c <c-file-name>] [-e <exec-file>] ",
241	    "<conffile>");
242	exit(1);
243}
244
245
246/*
247 * ========================================================================
248 * parse_conf_file subsystem
249 *
250 */
251
252/* helper routines for parse_conf_file */
253
254void parse_one_file(char *filename);
255void parse_line(char *pline, int *fc, char **fv, int nf);
256void add_srcdirs(int argc, char **argv);
257void add_progs(int argc, char **argv);
258void add_link(int argc, char **argv);
259void add_libs(int argc, char **argv);
260void add_libs_so(int argc, char **argv);
261void add_buildopts(int argc, char **argv);
262void add_special(int argc, char **argv);
263
264prog_t *find_prog(char *str);
265void add_prog(char *progname);
266
267
268void
269parse_conf_file(void)
270{
271	if (!is_nonempty_file(infilename))
272		errx(1, "fatal: input file \"%s\" not found", infilename);
273
274	parse_one_file(infilename);
275	if (readcache && is_nonempty_file(cachename)) {
276		reading_cache = 1;
277		parse_one_file(cachename);
278	}
279}
280
281
282void
283parse_one_file(char *filename)
284{
285	char *fieldv[MAXFIELDS];
286	int fieldc;
287	void (*f)(int c, char **v);
288	FILE *cf;
289	char line[MAXLINELEN];
290
291	snprintf(line, sizeof(line), "reading %s", filename);
292	status(line);
293	strlcpy(curfilename, filename, sizeof(curfilename));
294
295	if ((cf = fopen(curfilename, "r")) == NULL) {
296		warn("%s", curfilename);
297		goterror = 1;
298		return;
299	}
300
301	linenum = 0;
302	while (fgets(line, MAXLINELEN, cf) != NULL) {
303		linenum++;
304		parse_line(line, &fieldc, fieldv, MAXFIELDS);
305
306		if (fieldc < 1)
307			continue;
308
309		if (!strcmp(fieldv[0], "srcdirs"))
310			f = add_srcdirs;
311		else if(!strcmp(fieldv[0], "progs"))
312			f = add_progs;
313		else if(!strcmp(fieldv[0], "ln"))
314			f = add_link;
315		else if(!strcmp(fieldv[0], "libs"))
316			f = add_libs;
317		else if(!strcmp(fieldv[0], "libs_so"))
318			f = add_libs_so;
319		else if(!strcmp(fieldv[0], "buildopts"))
320			f = add_buildopts;
321		else if(!strcmp(fieldv[0], "special"))
322			f = add_special;
323		else {
324			warnx("%s:%d: skipping unknown command `%s'",
325			    curfilename, linenum, fieldv[0]);
326			goterror = 1;
327			continue;
328		}
329
330		if (fieldc < 2) {
331			warnx("%s:%d: %s %s",
332			    curfilename, linenum, fieldv[0],
333			    "command needs at least 1 argument, skipping");
334			goterror = 1;
335			continue;
336		}
337
338		f(fieldc, fieldv);
339	}
340
341	if (ferror(cf)) {
342		warn("%s", curfilename);
343		goterror = 1;
344	}
345	fclose(cf);
346}
347
348
349void
350parse_line(char *pline, int *fc, char **fv, int nf)
351{
352	char *p;
353
354	p = pline;
355	*fc = 0;
356
357	while (1) {
358		while (isspace((unsigned char)*p))
359			p++;
360
361		if (*p == '\0' || *p == '#')
362			break;
363
364		if (*fc < nf)
365			fv[(*fc)++] = p;
366
367		while (*p && !isspace((unsigned char)*p) && *p != '#')
368			p++;
369
370		if (*p == '\0' || *p == '#')
371			break;
372
373		*p++ = '\0';
374	}
375
376	if (*p)
377		*p = '\0';		/* needed for '#' case */
378}
379
380
381void
382add_srcdirs(int argc, char **argv)
383{
384	int i;
385
386	for (i = 1; i < argc; i++) {
387		if (is_dir(argv[i]))
388			add_string(&srcdirs, argv[i]);
389		else {
390			warnx("%s:%d: `%s' is not a directory, skipping it",
391			    curfilename, linenum, argv[i]);
392			goterror = 1;
393		}
394	}
395}
396
397
398void
399add_progs(int argc, char **argv)
400{
401	int i;
402
403	for (i = 1; i < argc; i++)
404		add_prog(argv[i]);
405}
406
407
408void
409add_prog(char *progname)
410{
411	prog_t *p1, *p2;
412
413	/* add to end, but be smart about dups */
414
415	for (p1 = NULL, p2 = progs; p2 != NULL; p1 = p2, p2 = p2->next)
416		if (!strcmp(p2->name, progname))
417			return;
418
419	p2 = malloc(sizeof(prog_t));
420	if(p2) {
421		memset(p2, 0, sizeof(prog_t));
422		p2->name = strdup(progname);
423	}
424	if (!p2 || !p2->name)
425		out_of_memory();
426
427	p2->next = NULL;
428	if (p1 == NULL)
429		progs = p2;
430	else
431		p1->next = p2;
432
433	p2->ident = NULL;
434	p2->srcdir = NULL;
435	p2->realsrcdir = NULL;
436	p2->objdir = NULL;
437	p2->links = NULL;
438	p2->libs = NULL;
439	p2->libs_so = NULL;
440	p2->objs = NULL;
441	p2->keeplist = NULL;
442	p2->buildopts = NULL;
443	p2->goterror = 0;
444
445	if (list_mode)
446		printf("%s\n",progname);
447}
448
449
450void
451add_link(int argc, char **argv)
452{
453	int i;
454	prog_t *p = find_prog(argv[1]);
455
456	if (p == NULL) {
457		warnx("%s:%d: no prog %s previously declared, skipping link",
458		    curfilename, linenum, argv[1]);
459		goterror = 1;
460		return;
461	}
462
463	for (i = 2; i < argc; i++) {
464		if (list_mode)
465			printf("%s\n",argv[i]);
466
467		add_string(&p->links, argv[i]);
468	}
469}
470
471
472void
473add_libs(int argc, char **argv)
474{
475	int i;
476
477	for(i = 1; i < argc; i++) {
478		add_string(&libs, argv[i]);
479		if ( in_list(&libs_so, argv[i]) )
480			warnx("%s:%d: "
481				"library `%s' specified as dynamic earlier",
482				curfilename, linenum, argv[i]);
483	}
484}
485
486
487void
488add_libs_so(int argc, char **argv)
489{
490	int i;
491
492	for(i = 1; i < argc; i++) {
493		add_string(&libs_so, argv[i]);
494		if ( in_list(&libs, argv[i]) )
495			warnx("%s:%d: "
496				"library `%s' specified as static earlier",
497				curfilename, linenum, argv[i]);
498	}
499}
500
501
502void
503add_buildopts(int argc, char **argv)
504{
505	int i;
506
507	for (i = 1; i < argc; i++)
508		add_string(&buildopts, argv[i]);
509}
510
511
512void
513add_special(int argc, char **argv)
514{
515	int i;
516	prog_t *p = find_prog(argv[1]);
517
518	if (p == NULL) {
519		if (reading_cache)
520			return;
521
522		warnx("%s:%d: no prog %s previously declared, skipping special",
523		    curfilename, linenum, argv[1]);
524		goterror = 1;
525		return;
526	}
527
528	if (!strcmp(argv[2], "ident")) {
529		if (argc != 4)
530			goto argcount;
531		if ((p->ident = strdup(argv[3])) == NULL)
532			out_of_memory();
533	} else if (!strcmp(argv[2], "srcdir")) {
534		if (argc != 4)
535			goto argcount;
536		if ((p->srcdir = strdup(argv[3])) == NULL)
537			out_of_memory();
538	} else if (!strcmp(argv[2], "objdir")) {
539		if(argc != 4)
540			goto argcount;
541		if((p->objdir = strdup(argv[3])) == NULL)
542			out_of_memory();
543	} else if (!strcmp(argv[2], "objs")) {
544		p->objs = NULL;
545		for (i = 3; i < argc; i++)
546			add_string(&p->objs, argv[i]);
547	} else if (!strcmp(argv[2], "objpaths")) {
548		p->objpaths = NULL;
549		for (i = 3; i < argc; i++)
550			add_string(&p->objpaths, argv[i]);
551	} else if (!strcmp(argv[2], "keep")) {
552		p->keeplist = NULL;
553		for(i = 3; i < argc; i++)
554			add_string(&p->keeplist, argv[i]);
555	} else if (!strcmp(argv[2], "objvar")) {
556		if(argc != 4)
557			goto argcount;
558		if ((p->objvar = strdup(argv[3])) == NULL)
559			out_of_memory();
560	} else if (!strcmp(argv[2], "buildopts")) {
561		p->buildopts = NULL;
562		for (i = 3; i < argc; i++)
563			add_string(&p->buildopts, argv[i]);
564	} else if (!strcmp(argv[2], "lib")) {
565		for (i = 3; i < argc; i++)
566			add_string(&p->libs, argv[i]);
567	} else {
568		warnx("%s:%d: bad parameter name `%s', skipping line",
569		    curfilename, linenum, argv[2]);
570		goterror = 1;
571	}
572	return;
573
574 argcount:
575	warnx("%s:%d: too %s arguments, expected \"special %s %s <string>\"",
576	    curfilename, linenum, argc < 4? "few" : "many", argv[1], argv[2]);
577	goterror = 1;
578}
579
580
581prog_t *find_prog(char *str)
582{
583	prog_t *p;
584
585	for (p = progs; p != NULL; p = p->next)
586		if (!strcmp(p->name, str))
587			return p;
588
589	return NULL;
590}
591
592
593/*
594 * ========================================================================
595 * gen_outputs subsystem
596 *
597 */
598
599/* helper subroutines */
600
601void remove_error_progs(void);
602void fillin_program(prog_t *p);
603void gen_specials_cache(void);
604void gen_output_makefile(void);
605void gen_output_cfile(void);
606
607void fillin_program_objs(prog_t *p, char *path);
608void top_makefile_rules(FILE *outmk);
609void prog_makefile_rules(FILE *outmk, prog_t *p);
610void output_strlst(FILE *outf, strlst_t *lst);
611char *genident(char *str);
612char *dir_search(char *progname);
613
614
615void
616gen_outputs(void)
617{
618	prog_t *p;
619
620	for (p = progs; p != NULL; p = p->next)
621		fillin_program(p);
622
623	remove_error_progs();
624	gen_specials_cache();
625	gen_output_cfile();
626	gen_output_makefile();
627	status("");
628	fprintf(stderr,
629	    "Run \"%s -f %s\" to build crunched binary.\n",
630	    path_make, outmkname);
631}
632
633/*
634 * run the makefile for the program to find which objects are necessary
635 */
636void
637fillin_program(prog_t *p)
638{
639	char path[MAXPATHLEN];
640	char line[MAXLINELEN];
641	FILE *f;
642
643	snprintf(line, MAXLINELEN, "filling in parms for %s", p->name);
644	status(line);
645
646	if (!p->ident)
647		p->ident = genident(p->name);
648
649	/* look for the source directory if one wasn't specified by a special */
650	if (!p->srcdir) {
651		p->srcdir = dir_search(p->name);
652	}
653
654	/* Determine the actual srcdir (maybe symlinked). */
655	if (p->srcdir) {
656		snprintf(line, MAXLINELEN, "cd %s && pwd -P", p->srcdir);
657		f = popen(line,"r");
658		if (!f)
659			errx(1, "Can't execute: %s\n", line);
660
661		path[0] = '\0';
662		fgets(path, sizeof path, f);
663		if (pclose(f))
664			errx(1, "Can't execute: %s\n", line);
665
666		if (!*path)
667			errx(1, "Can't perform pwd on: %s\n", p->srcdir);
668
669		/* Chop off trailing newline. */
670		path[strlen(path) - 1] = '\0';
671		p->realsrcdir = strdup(path);
672	}
673
674	/* Unless the option to make object files was specified the
675	* the objects will be built in the source directory unless
676	* an object directory already exists.
677	*/
678	if (!makeobj && !p->objdir && p->srcdir) {
679		char *auto_obj;
680
681		auto_obj = NULL;
682		snprintf(line, sizeof line, "%s/%s", objprefix, p->realsrcdir);
683		if (is_dir(line) ||
684		    ((auto_obj = getenv("MK_AUTO_OBJ")) != NULL &&
685		    strcmp(auto_obj, "yes") == 0)) {
686			if ((p->objdir = strdup(line)) == NULL)
687			out_of_memory();
688		} else
689			p->objdir = p->realsrcdir;
690	}
691
692	/*
693	* XXX look for a Makefile.{name} in local directory first.
694	* This lets us override the original Makefile.
695	*/
696	snprintf(path, sizeof(path), "Makefile.%s", p->name);
697	if (is_nonempty_file(path)) {
698		snprintf(line, MAXLINELEN, "Using %s for %s", path, p->name);
699		status(line);
700	} else
701		if (p->srcdir)
702			snprintf(path, sizeof(path), "%s/Makefile", p->srcdir);
703	if (!p->objs && p->srcdir && is_nonempty_file(path))
704		fillin_program_objs(p, path);
705
706	if (!p->srcdir && !p->objdir && verbose)
707		warnx("%s: %s: %s",
708		    "warning: could not find source directory",
709		    infilename, p->name);
710	if (!p->objs && verbose)
711		warnx("%s: %s: warning: could not find any .o files",
712		    infilename, p->name);
713
714	if ((!p->srcdir || !p->objdir) && !p->objs)
715		p->goterror = 1;
716}
717
718void
719fillin_program_objs(prog_t *p, char *path)
720{
721	char *obj, *cp;
722	int fd, rc;
723	FILE *f;
724	char *objvar="OBJS";
725	strlst_t *s;
726	char line[MAXLINELEN];
727
728	/* discover the objs from the srcdir Makefile */
729
730	/*
731	 * We reuse the same temporary file name for multiple objects. However,
732	 * some libc implementations (such as glibc) return EINVAL if there
733	 * are no XXXXX characters in the template. This happens after the
734	 * first call to mkstemp since the argument is modified in-place.
735	 * To avoid this error we use open() instead of mkstemp() after the
736	 * call to mkstemp().
737	 */
738	if (tempfname_initialized) {
739		if ((fd = open(tempfname, O_CREAT | O_EXCL | O_RDWR, 0600)) == -1) {
740			err(EX_OSERR, "open(%s)", tempfname);
741		}
742	} else if ((fd = mkstemp(tempfname)) == -1) {
743		err(EX_OSERR, "mkstemp(%s)", tempfname);
744	}
745	tempfname_initialized = true;
746	if ((f = fdopen(fd, "w")) == NULL) {
747		warn("fdopen(%s)", tempfname);
748		goterror = 1;
749		goto out;
750	}
751	if (p->objvar)
752		objvar = p->objvar;
753
754	/*
755	* XXX include outhdrname (e.g. to contain Make variables)
756	*/
757	if (outhdrname[0] != '\0')
758		fprintf(f, ".include \"%s\"\n", outhdrname);
759	fprintf(f, ".include \"%s\"\n", path);
760	fprintf(f, ".POSIX:\n");
761	if (buildopts) {
762		fprintf(f, "BUILDOPTS+=");
763		output_strlst(f, buildopts);
764	}
765	fprintf(f, ".if defined(PROG)\n");
766	fprintf(f, "%s?=${PROG}.o\n", objvar);
767	fprintf(f, ".endif\n");
768	fprintf(f, "loop:\n\t@echo 'OBJS= '${%s}\n", objvar);
769
770	fprintf(f, "crunchgen_objs:\n"
771	    "\t@cd %s && %s -f %s $(BUILDOPTS) $(%s_OPTS)",
772	    p->srcdir, path_make, tempfname, p->ident);
773	for (s = p->buildopts; s != NULL; s = s->next)
774		fprintf(f, " %s", s->str);
775	fprintf(f, " loop\n");
776
777	fclose(f);
778
779	snprintf(line, MAXLINELEN, "cd %s && %s -f %s -B crunchgen_objs",
780	     p->srcdir, path_make, tempfname);
781	if ((f = popen(line, "r")) == NULL) {
782		warn("submake pipe");
783		goterror = 1;
784		goto out;
785	}
786
787	while(fgets(line, MAXLINELEN, f)) {
788		if (strncmp(line, "OBJS= ", 6)) {
789			warnx("make error: %s", line);
790			goterror = 1;
791			goto out;
792		}
793
794		cp = line + 6;
795		while (isspace((unsigned char)*cp))
796			cp++;
797
798		while(*cp) {
799			obj = cp;
800			while (*cp && !isspace((unsigned char)*cp))
801				cp++;
802			if (*cp)
803				*cp++ = '\0';
804			add_string(&p->objs, obj);
805			while (isspace((unsigned char)*cp))
806				cp++;
807		}
808	}
809
810	if ((rc=pclose(f)) != 0) {
811		warnx("make error: make returned %d", rc);
812		goterror = 1;
813	}
814out:
815	unlink(tempfname);
816}
817
818void
819remove_error_progs(void)
820{
821	prog_t *p1, *p2;
822
823	p1 = NULL; p2 = progs;
824	while (p2 != NULL) {
825		if (!p2->goterror)
826			p1 = p2, p2 = p2->next;
827		else {
828			/* delete it from linked list */
829			warnx("%s: %s: ignoring program because of errors",
830			    infilename, p2->name);
831			if (p1)
832				p1->next = p2->next;
833			else
834				progs = p2->next;
835			p2 = p2->next;
836		}
837	}
838}
839
840void
841gen_specials_cache(void)
842{
843	FILE *cachef;
844	prog_t *p;
845	char line[MAXLINELEN];
846
847	snprintf(line, MAXLINELEN, "generating %s", cachename);
848	status(line);
849
850	if ((cachef = fopen(cachename, "w")) == NULL) {
851		warn("%s", cachename);
852		goterror = 1;
853		return;
854	}
855
856	fprintf(cachef, "# %s - parm cache generated from %s by crunchgen "
857	    " %s\n\n",
858	    cachename, infilename, CRUNCH_VERSION);
859
860	for (p = progs; p != NULL; p = p->next) {
861		fprintf(cachef, "\n");
862		if (p->srcdir)
863			fprintf(cachef, "special %s srcdir %s\n",
864			    p->name, p->srcdir);
865		if (p->objdir)
866			fprintf(cachef, "special %s objdir %s\n",
867			    p->name, p->objdir);
868		if (p->objs) {
869			fprintf(cachef, "special %s objs", p->name);
870			output_strlst(cachef, p->objs);
871		}
872		if (p->objpaths) {
873			fprintf(cachef, "special %s objpaths", p->name);
874			output_strlst(cachef, p->objpaths);
875		}
876	}
877	fclose(cachef);
878}
879
880
881void
882gen_output_makefile(void)
883{
884	prog_t *p;
885	FILE *outmk;
886	char line[MAXLINELEN];
887
888	snprintf(line, MAXLINELEN, "generating %s", outmkname);
889	status(line);
890
891	if ((outmk = fopen(outmkname, "w")) == NULL) {
892		warn("%s", outmkname);
893		goterror = 1;
894		return;
895	}
896
897	fprintf(outmk, "# %s - generated from %s by crunchgen %s\n\n",
898	    outmkname, infilename, CRUNCH_VERSION);
899
900	if (outhdrname[0] != '\0')
901		fprintf(outmk, ".include \"%s\"\n", outhdrname);
902
903	top_makefile_rules(outmk);
904	for (p = progs; p != NULL; p = p->next)
905		prog_makefile_rules(outmk, p);
906
907	fprintf(outmk, "\n# ========\n");
908	fclose(outmk);
909}
910
911
912void
913gen_output_cfile(void)
914{
915	char **cp;
916	FILE *outcf;
917	prog_t *p;
918	strlst_t *s;
919	char line[MAXLINELEN];
920
921	snprintf(line, MAXLINELEN, "generating %s", outcfname);
922	status(line);
923
924	if((outcf = fopen(outcfname, "w")) == NULL) {
925		warn("%s", outcfname);
926		goterror = 1;
927		return;
928	}
929
930	fprintf(outcf,
931	    "/* %s - generated from %s by crunchgen %s */\n",
932	    outcfname, infilename, CRUNCH_VERSION);
933
934	fprintf(outcf, "#define EXECNAME \"%s\"\n", execfname);
935	for (cp = crunched_skel; *cp != NULL; cp++)
936		fprintf(outcf, "%s\n", *cp);
937
938	for (p = progs; p != NULL; p = p->next)
939		fprintf(outcf,
940		    "extern crunched_stub_t _crunched_%s_stub;\n",
941		    p->ident);
942
943	fprintf(outcf, "\nstruct stub entry_points[] = {\n");
944	for (p = progs; p != NULL; p = p->next) {
945		fprintf(outcf, "\t{ \"%s\", _crunched_%s_stub },\n",
946		    p->name, p->ident);
947		for (s = p->links; s != NULL; s = s->next)
948			fprintf(outcf, "\t{ \"%s\", _crunched_%s_stub },\n",
949			    s->str, p->ident);
950	}
951
952	fprintf(outcf, "\t{ EXECNAME, crunched_main },\n");
953	fprintf(outcf, "\t{ NULL, NULL }\n};\n");
954	fclose(outcf);
955}
956
957
958char *genident(char *str)
959{
960	char *n, *s, *d;
961
962	/*
963	 * generates a Makefile/C identifier from a program name,
964	 * mapping '-' to '_' and ignoring all other non-identifier
965	 * characters.  This leads to programs named "foo.bar" and
966	 * "foobar" to map to the same identifier.
967	 */
968
969	if ((n = strdup(str)) == NULL)
970		return NULL;
971	for (d = s = n; *s != '\0'; s++) {
972		if (*s == '-')
973			*d++ = '_';
974		else if (*s == '_' || isalnum((unsigned char)*s))
975			*d++ = *s;
976	}
977	*d = '\0';
978	return n;
979}
980
981
982char *dir_search(char *progname)
983{
984	char path[MAXPATHLEN];
985	strlst_t *dir;
986	char *srcdir;
987
988	for (dir = srcdirs; dir != NULL; dir = dir->next) {
989		snprintf(path, MAXPATHLEN, "%s/%s", dir->str, progname);
990		if (!is_dir(path))
991			continue;
992
993		if ((srcdir = strdup(path)) == NULL)
994			out_of_memory();
995
996		return srcdir;
997	}
998	return NULL;
999}
1000
1001
1002void
1003top_makefile_rules(FILE *outmk)
1004{
1005	prog_t *p;
1006
1007	fprintf(outmk, "LD?= ld\n");
1008	if ( subtract_strlst(&libs, &libs_so) )
1009		fprintf(outmk, "# NOTE: Some LIBS declarations below overridden by LIBS_SO\n");
1010
1011	fprintf(outmk, "LIBS+=");
1012	output_strlst(outmk, libs);
1013
1014	fprintf(outmk, "LIBS_SO+=");
1015	output_strlst(outmk, libs_so);
1016
1017	if (makeobj) {
1018		fprintf(outmk, "MAKEOBJDIRPREFIX?=%s\n", objprefix);
1019		fprintf(outmk, "MAKEENV=env MAKEOBJDIRPREFIX=$(MAKEOBJDIRPREFIX)\n");
1020		fprintf(outmk, "CRUNCHMAKE=$(MAKEENV) $(MAKE)\n");
1021	} else {
1022		fprintf(outmk, "CRUNCHMAKE=$(MAKE)\n");
1023	}
1024
1025	if (buildopts) {
1026		fprintf(outmk, "BUILDOPTS+=");
1027		output_strlst(outmk, buildopts);
1028	}
1029
1030	fprintf(outmk, "CRUNCHED_OBJS=");
1031	for (p = progs; p != NULL; p = p->next)
1032		fprintf(outmk, " %s.lo", p->name);
1033	fprintf(outmk, "\n");
1034
1035	fprintf(outmk, "SUBMAKE_TARGETS=");
1036	for (p = progs; p != NULL; p = p->next)
1037		fprintf(outmk, " %s_make", p->ident);
1038	fprintf(outmk, "\nSUBCLEAN_TARGETS=");
1039	for (p = progs; p != NULL; p = p->next)
1040		fprintf(outmk, " %s_clean", p->ident);
1041	fprintf(outmk, "\n\n");
1042
1043	fprintf(outmk, "all: objs exe\nobjs: $(SUBMAKE_TARGETS)\n");
1044	fprintf(outmk, "exe: %s\n", execfname);
1045	fprintf(outmk, "%s: %s.o $(CRUNCHED_OBJS) $(SUBMAKE_TARGETS)\n", execfname, execfname);
1046	fprintf(outmk, ".if defined(LIBS_SO) && !empty(LIBS_SO)\n");
1047	fprintf(outmk, "\t$(CC) -o %s %s.o $(CRUNCHED_OBJS) \\\n",
1048	    execfname, execfname);
1049	fprintf(outmk, "\t\t-Xlinker -Bstatic $(LIBS) \\\n");
1050	fprintf(outmk, "\t\t-Xlinker -Bdynamic $(LIBS_SO)\n");
1051	fprintf(outmk, ".else\n");
1052	fprintf(outmk, "\t$(CC) -static -o %s %s.o $(CRUNCHED_OBJS) $(LIBS)\n",
1053	    execfname, execfname);
1054	fprintf(outmk, ".endif\n");
1055	fprintf(outmk, "realclean: clean subclean\n");
1056	fprintf(outmk, "clean:\n\trm -f %s *.lo *.o *_stub.c\n", execfname);
1057	fprintf(outmk, "subclean: $(SUBCLEAN_TARGETS)\n");
1058}
1059
1060
1061void
1062prog_makefile_rules(FILE *outmk, prog_t *p)
1063{
1064	strlst_t *lst;
1065
1066	fprintf(outmk, "\n# -------- %s\n\n", p->name);
1067
1068	fprintf(outmk, "%s_OBJDIR=", p->ident);
1069	if (p->objdir)
1070		fprintf(outmk, "%s", p->objdir);
1071	else
1072		fprintf(outmk, "$(MAKEOBJDIRPREFIX)/$(%s_REALSRCDIR)\n",
1073		    p->ident);
1074	fprintf(outmk, "\n");
1075
1076	fprintf(outmk, "%s_OBJPATHS=", p->ident);
1077	if (p->objpaths)
1078		output_strlst(outmk, p->objpaths);
1079	else {
1080		for (lst = p->objs; lst != NULL; lst = lst->next) {
1081			fprintf(outmk, " $(%s_OBJDIR)/%s", p->ident, lst->str);
1082		}
1083		fprintf(outmk, "\n");
1084	}
1085	fprintf(outmk, "$(%s_OBJPATHS): .NOMETA\n", p->ident);
1086
1087	if (p->srcdir && p->objs) {
1088		fprintf(outmk, "%s_SRCDIR=%s\n", p->ident, p->srcdir);
1089		fprintf(outmk, "%s_REALSRCDIR=%s\n", p->ident, p->realsrcdir);
1090
1091		fprintf(outmk, "%s_OBJS=", p->ident);
1092		output_strlst(outmk, p->objs);
1093		if (p->buildopts != NULL) {
1094			fprintf(outmk, "%s_OPTS+=", p->ident);
1095			output_strlst(outmk, p->buildopts);
1096		}
1097#if 0
1098		fprintf(outmk, "$(%s_OBJPATHS): %s_make\n\n", p->ident, p->ident);
1099#endif
1100		fprintf(outmk, "%s_make:\n", p->ident);
1101		fprintf(outmk, "\t(cd $(%s_SRCDIR) && ", p->ident);
1102		if (makeobj)
1103			fprintf(outmk, "$(CRUNCHMAKE) obj && ");
1104		fprintf(outmk, "\\\n");
1105		fprintf(outmk, "\t\t$(CRUNCHMAKE) $(BUILDOPTS) $(%s_OPTS) depend &&",
1106		    p->ident);
1107		fprintf(outmk, "\\\n");
1108		fprintf(outmk, "\t\t$(CRUNCHMAKE) $(BUILDOPTS) $(%s_OPTS) "
1109		    "$(%s_OBJS))",
1110		    p->ident, p->ident);
1111		fprintf(outmk, "\n");
1112		fprintf(outmk, "%s_clean:\n", p->ident);
1113		fprintf(outmk, "\t(cd $(%s_SRCDIR) && $(CRUNCHMAKE) $(BUILDOPTS) clean cleandepend)\n\n",
1114		    p->ident);
1115	} else {
1116		fprintf(outmk, "%s_make:\n", p->ident);
1117		fprintf(outmk, "\t@echo \"** cannot make objs for %s\"\n\n",
1118		    p->name);
1119	}
1120
1121	if (p->libs) {
1122		fprintf(outmk, "%s_LIBS=", p->ident);
1123		output_strlst(outmk, p->libs);
1124	}
1125
1126	fprintf(outmk, "%s_stub.c:\n", p->name);
1127	fprintf(outmk, "\techo \""
1128	    "extern int main(int argc, char **argv, char **envp); "
1129	    "int _crunched_%s_stub(int argc, char **argv, char **envp);"
1130	    "int _crunched_%s_stub(int argc, char **argv, char **envp)"
1131	    "{return main(argc,argv,envp);}\" >%s_stub.c\n",
1132	    p->ident, p->ident, p->name);
1133	fprintf(outmk, "%s.lo: %s_stub.o $(%s_OBJPATHS)",
1134	    p->name, p->name, p->ident);
1135	if (p->libs)
1136		fprintf(outmk, " $(%s_LIBS)", p->ident);
1137
1138	fprintf(outmk, "\n");
1139	fprintf(outmk, "\t$(CC) -nostdlib -Wl,-dc -r -o %s.lo %s_stub.o $(%s_OBJPATHS)",
1140	    p->name, p->name, p->ident);
1141	if (p->libs)
1142		fprintf(outmk, " $(%s_LIBS)", p->ident);
1143	fprintf(outmk, "\n");
1144	fprintf(outmk, "\tcrunchide -k _crunched_%s_stub ", p->ident);
1145	for (lst = p->keeplist; lst != NULL; lst = lst->next)
1146		fprintf(outmk, "-k _%s ", lst->str);
1147	fprintf(outmk, "%s.lo\n", p->name);
1148}
1149
1150void
1151output_strlst(FILE *outf, strlst_t *lst)
1152{
1153	for (; lst != NULL; lst = lst->next)
1154		if ( strlen(lst->str) )
1155			fprintf(outf, " %s", lst->str);
1156	fprintf(outf, "\n");
1157}
1158
1159
1160/*
1161 * ========================================================================
1162 * general library routines
1163 *
1164 */
1165
1166void
1167status(const char *str)
1168{
1169	static int lastlen = 0;
1170	int len, spaces;
1171
1172	if (!verbose)
1173		return;
1174
1175	len = strlen(str);
1176	spaces = lastlen - len;
1177	if (spaces < 1)
1178		spaces = 1;
1179
1180	fprintf(stderr, " [%s]%*.*s\r", str, spaces, spaces, " ");
1181	fflush(stderr);
1182	lastlen = len;
1183}
1184
1185
1186void
1187out_of_memory(void)
1188{
1189	err(1, "%s: %d: out of memory, stopping", infilename, linenum);
1190}
1191
1192
1193void
1194add_string(strlst_t **listp, char *str)
1195{
1196	strlst_t *p1, *p2;
1197
1198	/* add to end, but be smart about dups */
1199
1200	for (p1 = NULL, p2 = *listp; p2 != NULL; p1 = p2, p2 = p2->next)
1201		if (!strcmp(p2->str, str))
1202			return;
1203
1204	p2 = malloc(sizeof(strlst_t));
1205	if (p2) {
1206		p2->next = NULL;
1207		p2->str = strdup(str);
1208    	}
1209	if (!p2 || !p2->str)
1210		out_of_memory();
1211
1212	if (p1 == NULL)
1213		*listp = p2;
1214	else
1215		p1->next = p2;
1216}
1217
1218int
1219subtract_strlst(strlst_t **lista, strlst_t **listb)
1220{
1221	int subtract_count = 0;
1222	strlst_t *p1;
1223	for (p1 = *listb; p1 != NULL; p1 = p1->next)
1224		if ( in_list(lista, p1->str) ) {
1225			warnx("Will compile library `%s' dynamically", p1->str);
1226			strcat(p1->str, "");
1227			subtract_count++;
1228		}
1229	return subtract_count;
1230}
1231
1232int
1233in_list(strlst_t **listp, char *str)
1234{
1235	strlst_t *p1;
1236	for (p1 = *listp; p1 != NULL; p1 = p1->next)
1237		if (!strcmp(p1->str, str))
1238			return 1;
1239	return 0;
1240}
1241
1242int
1243is_dir(const char *pathname)
1244{
1245	struct stat buf;
1246
1247	if (stat(pathname, &buf) == -1)
1248		return 0;
1249
1250	return S_ISDIR(buf.st_mode);
1251}
1252
1253int
1254is_nonempty_file(const char *pathname)
1255{
1256	struct stat buf;
1257
1258	if (stat(pathname, &buf) == -1)
1259		return 0;
1260
1261	return S_ISREG(buf.st_mode) && buf.st_size > 0;
1262}
1263