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