xref: /freebsd/usr.sbin/crunch/crunchgen/crunchgen.c (revision fd45b686f9d92f583366c75b22c04c7ee49709c0)
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 
58 typedef 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 
65 typedef 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 
85 static strlst_t *buildopts = NULL;
86 static strlst_t *srcdirs   = NULL;
87 static strlst_t *libs      = NULL;
88 static strlst_t *libs_so   = NULL;
89 static prog_t   *progs     = NULL;
90 
91 static char confname[MAXPATHLEN], infilename[MAXPATHLEN];
92 static char outmkname[MAXPATHLEN], outcfname[MAXPATHLEN], execfname[MAXPATHLEN];
93 static char tempfname[MAXPATHLEN], cachename[MAXPATHLEN];
94 static char curfilename[MAXPATHLEN];
95 static bool tempfname_initialized = false;
96 static char outhdrname[MAXPATHLEN] ;	/* user-supplied header for *.mk */
97 static const char *objprefix;		/* where are the objects ? */
98 static const char *path_make;
99 static int linenum = -1;
100 static int goterror = 0;
101 
102 static int verbose, readcache;	/* options */
103 static int reading_cache;
104 static int makeobj = 0;		/* add 'make obj' rules to the makefile */
105 
106 static int list_mode;
107 
108 /* general library routines */
109 
110 void status(const char *str);
111 void out_of_memory(void);
112 void add_string(strlst_t **listp, char *str);
113 int is_dir(const char *pathname);
114 int is_nonempty_file(const char *pathname);
115 int subtract_strlst(strlst_t **lista, strlst_t **listb);
116 int in_list(strlst_t **listp, char *str);
117 
118 /* helper routines for main() */
119 
120 void usage(void);
121 void parse_conf_file(void);
122 void gen_outputs(void);
123 
124 extern const char *crunched_skel[];
125 
126 
127 int
128 main(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 
233 void
234 usage(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 
252 void parse_one_file(char *filename);
253 void parse_line(char *pline, int *fc, char **fv, int nf);
254 void add_srcdirs(int argc, char **argv);
255 void add_progs(int argc, char **argv);
256 void add_link(int argc, char **argv);
257 void add_libs(int argc, char **argv);
258 void add_libs_so(int argc, char **argv);
259 void add_buildopts(int argc, char **argv);
260 void add_special(int argc, char **argv);
261 
262 prog_t *find_prog(char *str);
263 void add_prog(char *progname);
264 
265 
266 void
267 parse_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 
280 void
281 parse_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 
347 void
348 parse_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 
379 void
380 add_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 
396 void
397 add_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 
406 void
407 add_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 
448 void
449 add_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 
470 void
471 add_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 
485 void
486 add_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 
500 void
501 add_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 
510 void
511 add_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 
579 prog_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 
599 void remove_error_progs(void);
600 void fillin_program(prog_t *p);
601 void gen_specials_cache(void);
602 void gen_output_makefile(void);
603 void gen_output_cfile(void);
604 
605 void fillin_program_objs(prog_t *p, char *path);
606 void top_makefile_rules(FILE *outmk);
607 void prog_makefile_rules(FILE *outmk, prog_t *p);
608 void output_strlst(FILE *outf, strlst_t *lst);
609 char *genident(char *str);
610 char *dir_search(char *progname);
611 
612 
613 void
614 gen_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  */
634 void
635 fillin_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 	* the 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 
702 void
703 fillin_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 	}
798 out:
799 	unlink(tempfname);
800 }
801 
802 void
803 remove_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 
824 void
825 gen_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 
865 void
866 gen_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 
896 void
897 gen_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 	fprintf(outcf, "\nstruct stub entry_points[] = {\n");
928 	for (p = progs; p != NULL; p = p->next) {
929 		fprintf(outcf, "\t{ \"%s\", _crunched_%s_stub },\n",
930 		    p->name, p->ident);
931 		for (s = p->links; s != NULL; s = s->next)
932 			fprintf(outcf, "\t{ \"%s\", _crunched_%s_stub },\n",
933 			    s->str, p->ident);
934 	}
935 
936 	fprintf(outcf, "\t{ EXECNAME, crunched_main },\n");
937 	fprintf(outcf, "\t{ NULL, NULL }\n};\n");
938 	fclose(outcf);
939 }
940 
941 
942 char *genident(char *str)
943 {
944 	char *n, *s, *d;
945 
946 	/*
947 	 * generates a Makefile/C identifier from a program name,
948 	 * mapping '-' to '_' and ignoring all other non-identifier
949 	 * characters.  This leads to programs named "foo.bar" and
950 	 * "foobar" to map to the same identifier.
951 	 */
952 
953 	if ((n = strdup(str)) == NULL)
954 		return NULL;
955 	for (d = s = n; *s != '\0'; s++) {
956 		if (*s == '-')
957 			*d++ = '_';
958 		else if (*s == '_' || isalnum((unsigned char)*s))
959 			*d++ = *s;
960 	}
961 	*d = '\0';
962 	return n;
963 }
964 
965 
966 char *dir_search(char *progname)
967 {
968 	char path[MAXPATHLEN];
969 	strlst_t *dir;
970 	char *srcdir;
971 
972 	for (dir = srcdirs; dir != NULL; dir = dir->next) {
973 		snprintf(path, MAXPATHLEN, "%s/%s", dir->str, progname);
974 		if (!is_dir(path))
975 			continue;
976 
977 		if ((srcdir = strdup(path)) == NULL)
978 			out_of_memory();
979 
980 		return srcdir;
981 	}
982 	return NULL;
983 }
984 
985 
986 void
987 top_makefile_rules(FILE *outmk)
988 {
989 	prog_t *p;
990 
991 	fprintf(outmk, "LD?= ld\n");
992 	if ( subtract_strlst(&libs, &libs_so) )
993 		fprintf(outmk, "# NOTE: Some LIBS declarations below overridden by LIBS_SO\n");
994 
995 	fprintf(outmk, "LIBS+=");
996 	output_strlst(outmk, libs);
997 
998 	fprintf(outmk, "LIBS_SO+=");
999 	output_strlst(outmk, libs_so);
1000 
1001 	if (makeobj) {
1002 		fprintf(outmk, "MAKEOBJDIRPREFIX?=%s\n", objprefix);
1003 		fprintf(outmk, "MAKEENV=env MAKEOBJDIRPREFIX=$(MAKEOBJDIRPREFIX)\n");
1004 		fprintf(outmk, "CRUNCHMAKE=$(MAKEENV) $(MAKE)\n");
1005 	} else {
1006 		fprintf(outmk, "CRUNCHMAKE=$(MAKE)\n");
1007 	}
1008 
1009 	if (buildopts) {
1010 		fprintf(outmk, "BUILDOPTS+=");
1011 		output_strlst(outmk, buildopts);
1012 	}
1013 
1014 	fprintf(outmk, "CRUNCHED_OBJS=");
1015 	for (p = progs; p != NULL; p = p->next)
1016 		fprintf(outmk, " %s.lo", p->name);
1017 	fprintf(outmk, "\n");
1018 
1019 	fprintf(outmk, "SUBMAKE_TARGETS=");
1020 	for (p = progs; p != NULL; p = p->next)
1021 		fprintf(outmk, " %s_make", p->ident);
1022 	fprintf(outmk, "\nSUBCLEAN_TARGETS=");
1023 	for (p = progs; p != NULL; p = p->next)
1024 		fprintf(outmk, " %s_clean", p->ident);
1025 	fprintf(outmk, "\n\n");
1026 
1027 	fprintf(outmk, "all: objs exe\nobjs: $(SUBMAKE_TARGETS)\n");
1028 	fprintf(outmk, "exe: %s\n", execfname);
1029 	fprintf(outmk, "%s: %s.o $(CRUNCHED_OBJS) $(SUBMAKE_TARGETS)\n", execfname, execfname);
1030 	fprintf(outmk, ".if defined(LIBS_SO) && !empty(LIBS_SO)\n");
1031 	fprintf(outmk, "\t$(CC) -o %s %s.o $(CRUNCHED_OBJS) \\\n",
1032 	    execfname, execfname);
1033 	fprintf(outmk, "\t\t-Xlinker -Bstatic $(LIBS) \\\n");
1034 	fprintf(outmk, "\t\t-Xlinker -Bdynamic $(LIBS_SO)\n");
1035 	fprintf(outmk, ".else\n");
1036 	fprintf(outmk, "\t$(CC) -static -o %s %s.o $(CRUNCHED_OBJS) $(LIBS)\n",
1037 	    execfname, execfname);
1038 	fprintf(outmk, ".endif\n");
1039 	fprintf(outmk, "realclean: clean subclean\n");
1040 	fprintf(outmk, "clean:\n\trm -f %s *.lo *.o *_stub.c\n", execfname);
1041 	fprintf(outmk, "subclean: $(SUBCLEAN_TARGETS)\n");
1042 }
1043 
1044 
1045 void
1046 prog_makefile_rules(FILE *outmk, prog_t *p)
1047 {
1048 	strlst_t *lst;
1049 
1050 	fprintf(outmk, "\n# -------- %s\n\n", p->name);
1051 
1052 	fprintf(outmk, "%s_OBJDIR=", p->ident);
1053 	if (p->objdir)
1054 		fprintf(outmk, "%s", p->objdir);
1055 	else
1056 		fprintf(outmk, "$(MAKEOBJDIRPREFIX)/$(%s_REALSRCDIR)\n",
1057 		    p->ident);
1058 	fprintf(outmk, "\n");
1059 
1060 	fprintf(outmk, "%s_OBJPATHS=", p->ident);
1061 	if (p->objpaths)
1062 		output_strlst(outmk, p->objpaths);
1063 	else {
1064 		for (lst = p->objs; lst != NULL; lst = lst->next) {
1065 			fprintf(outmk, " $(%s_OBJDIR)/%s", p->ident, lst->str);
1066 		}
1067 		fprintf(outmk, "\n");
1068 	}
1069 	fprintf(outmk, "$(%s_OBJPATHS): .NOMETA\n", p->ident);
1070 
1071 	if (p->srcdir && p->objs) {
1072 		fprintf(outmk, "%s_SRCDIR=%s\n", p->ident, p->srcdir);
1073 		fprintf(outmk, "%s_REALSRCDIR=%s\n", p->ident, p->realsrcdir);
1074 
1075 		fprintf(outmk, "%s_OBJS=", p->ident);
1076 		output_strlst(outmk, p->objs);
1077 		if (p->buildopts != NULL) {
1078 			fprintf(outmk, "%s_OPTS+=", p->ident);
1079 			output_strlst(outmk, p->buildopts);
1080 		}
1081 #if 0
1082 		fprintf(outmk, "$(%s_OBJPATHS): %s_make\n\n", p->ident, p->ident);
1083 #endif
1084 		fprintf(outmk, "%s_make:\n", p->ident);
1085 		fprintf(outmk, "\t(cd $(%s_SRCDIR) && ", p->ident);
1086 		if (makeobj)
1087 			fprintf(outmk, "$(CRUNCHMAKE) obj && ");
1088 		fprintf(outmk, "\\\n");
1089 		fprintf(outmk, "\t\t$(CRUNCHMAKE) $(BUILDOPTS) $(%s_OPTS) depend &&",
1090 		    p->ident);
1091 		fprintf(outmk, "\\\n");
1092 		fprintf(outmk, "\t\t$(CRUNCHMAKE) $(BUILDOPTS) $(%s_OPTS) "
1093 		    "$(%s_OBJS))",
1094 		    p->ident, p->ident);
1095 		fprintf(outmk, "\n");
1096 		fprintf(outmk, "%s_clean:\n", p->ident);
1097 		fprintf(outmk, "\t(cd $(%s_SRCDIR) && $(CRUNCHMAKE) $(BUILDOPTS) clean cleandepend)\n\n",
1098 		    p->ident);
1099 	} else {
1100 		fprintf(outmk, "%s_make:\n", p->ident);
1101 		fprintf(outmk, "\t@echo \"** cannot make objs for %s\"\n\n",
1102 		    p->name);
1103 	}
1104 
1105 	if (p->libs) {
1106 		fprintf(outmk, "%s_LIBS=", p->ident);
1107 		output_strlst(outmk, p->libs);
1108 	}
1109 
1110 	fprintf(outmk, "%s_stub.c:\n", p->name);
1111 	fprintf(outmk, "\techo \""
1112 	    "extern int main(int argc, char **argv, char **envp); "
1113 	    "int _crunched_%s_stub(int argc, char **argv, char **envp);"
1114 	    "int _crunched_%s_stub(int argc, char **argv, char **envp)"
1115 	    "{return main(argc,argv,envp);}\" >%s_stub.c\n",
1116 	    p->ident, p->ident, p->name);
1117 	fprintf(outmk, "%s.lo: %s_stub.o $(%s_OBJPATHS)",
1118 	    p->name, p->name, p->ident);
1119 	if (p->libs)
1120 		fprintf(outmk, " $(%s_LIBS)", p->ident);
1121 
1122 	fprintf(outmk, "\n");
1123 	fprintf(outmk, "\t$(CC) -nostdlib -r -o %s.lo %s_stub.o $(%s_OBJPATHS)",
1124 	    p->name, p->name, p->ident);
1125 	if (p->libs)
1126 		fprintf(outmk, " $(%s_LIBS)", p->ident);
1127 	fprintf(outmk, "\n");
1128 	fprintf(outmk, "\tcrunchide -k _crunched_%s_stub ", p->ident);
1129 	for (lst = p->keeplist; lst != NULL; lst = lst->next)
1130 		fprintf(outmk, "-k %s ", lst->str);
1131 	fprintf(outmk, "%s.lo\n", p->name);
1132 }
1133 
1134 void
1135 output_strlst(FILE *outf, strlst_t *lst)
1136 {
1137 	for (; lst != NULL; lst = lst->next)
1138 		if ( strlen(lst->str) )
1139 			fprintf(outf, " %s", lst->str);
1140 	fprintf(outf, "\n");
1141 }
1142 
1143 
1144 /*
1145  * ========================================================================
1146  * general library routines
1147  *
1148  */
1149 
1150 void
1151 status(const char *str)
1152 {
1153 	static int lastlen = 0;
1154 	int len, spaces;
1155 
1156 	if (!verbose)
1157 		return;
1158 
1159 	len = strlen(str);
1160 	spaces = lastlen - len;
1161 	if (spaces < 1)
1162 		spaces = 1;
1163 
1164 	fprintf(stderr, " [%s]%*.*s\r", str, spaces, spaces, " ");
1165 	fflush(stderr);
1166 	lastlen = len;
1167 }
1168 
1169 
1170 void
1171 out_of_memory(void)
1172 {
1173 	err(1, "%s: %d: out of memory, stopping", infilename, linenum);
1174 }
1175 
1176 
1177 void
1178 add_string(strlst_t **listp, char *str)
1179 {
1180 	strlst_t *p1, *p2;
1181 
1182 	/* add to end, but be smart about dups */
1183 
1184 	for (p1 = NULL, p2 = *listp; p2 != NULL; p1 = p2, p2 = p2->next)
1185 		if (!strcmp(p2->str, str))
1186 			return;
1187 
1188 	p2 = malloc(sizeof(strlst_t));
1189 	if (p2) {
1190 		p2->next = NULL;
1191 		p2->str = strdup(str);
1192     	}
1193 	if (!p2 || !p2->str)
1194 		out_of_memory();
1195 
1196 	if (p1 == NULL)
1197 		*listp = p2;
1198 	else
1199 		p1->next = p2;
1200 }
1201 
1202 int
1203 subtract_strlst(strlst_t **lista, strlst_t **listb)
1204 {
1205 	int subtract_count = 0;
1206 	strlst_t *p1;
1207 	for (p1 = *listb; p1 != NULL; p1 = p1->next)
1208 		if ( in_list(lista, p1->str) ) {
1209 			warnx("Will compile library `%s' dynamically", p1->str);
1210 			strcat(p1->str, "");
1211 			subtract_count++;
1212 		}
1213 	return subtract_count;
1214 }
1215 
1216 int
1217 in_list(strlst_t **listp, char *str)
1218 {
1219 	strlst_t *p1;
1220 	for (p1 = *listp; p1 != NULL; p1 = p1->next)
1221 		if (!strcmp(p1->str, str))
1222 			return 1;
1223 	return 0;
1224 }
1225 
1226 int
1227 is_dir(const char *pathname)
1228 {
1229 	struct stat buf;
1230 
1231 	if (stat(pathname, &buf) == -1)
1232 		return 0;
1233 
1234 	return S_ISDIR(buf.st_mode);
1235 }
1236 
1237 int
1238 is_nonempty_file(const char *pathname)
1239 {
1240 	struct stat buf;
1241 
1242 	if (stat(pathname, &buf) == -1)
1243 		return 0;
1244 
1245 	return S_ISREG(buf.st_mode) && buf.st_size > 0;
1246 }
1247