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