xref: /netbsd-src/usr.bin/crunch/crunchgen/crunchgen.c (revision b7b7574d3bf8eeb51a1fa3977b59142ec6434a55)
1 /*	$NetBSD: crunchgen.c,v 1.82 2014/01/04 08:58:51 martin 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.82 2014/01/04 08:58:51 martin 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 static strlst_t *srcdirs = NULL;
87 static strlst_t *libs    = NULL;
88 static strlst_t *vars	  = NULL;
89 static prog_t   *progs   = NULL;
90 
91 static char line[MAXLINELEN];
92 
93 static char confname[MAXPATHLEN], infilename[MAXPATHLEN];
94 static char outmkname[MAXPATHLEN], outcfname[MAXPATHLEN], execfname[MAXPATHLEN];
95 static char cachename[MAXPATHLEN], curfilename[MAXPATHLEN];
96 static char curdir[MAXPATHLEN];
97 static char topdir[MAXPATHLEN];
98 static char libdir[MAXPATHLEN] = "/usr/lib";
99 static char dbg[MAXPATHLEN] = "-Os";
100 static int linenum = -1;
101 static int goterror = 0;
102 
103 static const char *pname = "crunchgen";
104 
105 static int verbose, readcache, useobjs, oneobj;	/* options */
106 static int reading_cache;
107 static char *machine;
108 static char *makeobjdirprefix;
109 static char *makebin;
110 static char *makeflags;
111 
112 /* general library routines */
113 
114 static void status(const char *str);
115 __dead static void out_of_memory(void);
116 static void add_string(strlst_t **listp, char *str);
117 static int is_dir(const char *pathname);
118 static int is_nonempty_file(const char *pathname);
119 
120 /* helper routines for main() */
121 
122 __dead static void usage(void);
123 static void parse_conf_file(void);
124 static 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 static void parse_one_file(char *filename);
238 static void parse_line(char *line, int *fc, char **fv, int nf);
239 static void add_srcdirs(int argc, char **argv);
240 static void add_progs(int argc, char **argv);
241 static void add_link(int argc, char **argv);
242 static void add_libs(int argc, char **argv);
243 static void add_special(int argc, char **argv);
244 
245 static prog_t *find_prog(char *str);
246 static void add_prog(char *progname);
247 
248 
249 static 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 static 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 static void
319 parse_line(char *pline, int *fc, char **fv, int nf)
320 {
321     char *p;
322 
323     p = pline;
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 static 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 static 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 static 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 static 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 static 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 static 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 	for (i = 3; i < argc; i++)
494 	    add_string(&p->objs, argv[i]);
495 	return;
496     }
497 
498     if (!strcmp(argv[2], "objpaths")) {
499 	oneobj = 0;
500 	for (i = 3; i < argc; i++)
501 	    add_string(&p->objpaths, argv[i]);
502 	return;
503     }
504 
505     if (!strcmp(argv[2], "keepsymbols")) {
506 	for (i = 3; i < argc; i++)
507 	    add_string(&p->keepsymbols, argv[i]);
508 	return;
509     }
510 
511     fprintf(stderr, "%s:%d: bad parameter name `%s', skipping line.\n",
512 	    curfilename, linenum, argv[2]);
513     goterror = 1;
514     return;
515 
516  argcount:
517     fprintf(stderr,
518 	    "%s:%d: too %s arguments, expected \"special %s %s <string>\".\n",
519 	    curfilename, linenum, argc < 4? "few" : "many", argv[1], argv[2]);
520     goterror = 1;
521 }
522 
523 
524 static prog_t *
525 find_prog(char *str)
526 {
527     prog_t *p;
528 
529     for (p = progs; p != NULL; p = p->next)
530 	if (!strcmp(p->name, str))
531 	    return p;
532 
533     return NULL;
534 }
535 
536 
537 /*
538  * ========================================================================
539  * gen_outputs subsystem
540  *
541  */
542 
543 /* helper subroutines */
544 
545 static void remove_error_progs(void);
546 static void fillin_program(prog_t *p);
547 static void gen_specials_cache(void);
548 static void gen_output_makefile(void);
549 static void gen_output_cfile(void);
550 
551 static void fillin_program_objs(prog_t *p, char *path);
552 static void top_makefile_rules(FILE *outmk);
553 static void bottom_makefile_rules(FILE *outmk);
554 static void prog_makefile_rules(FILE *outmk, prog_t *p);
555 static void output_strlst(FILE *outf, strlst_t *lst);
556 static char *genident(char *str);
557 static char *dir_search(char *progname);
558 
559 
560 static void
561 gen_outputs(void)
562 {
563     prog_t *p;
564 
565     for (p = progs; p != NULL; p = p->next)
566 	fillin_program(p);
567 
568     remove_error_progs();
569     gen_specials_cache();
570     gen_output_cfile();
571     gen_output_makefile();
572     status("");
573     fprintf(stderr,
574 	    "Run \"make -f %s objs exe\" to build crunched binary.\n",
575 	    outmkname);
576 }
577 
578 
579 static void
580 fillin_program(prog_t *p)
581 {
582     char path[MAXPATHLEN];
583     char *srcparent;
584     strlst_t *s;
585 
586     (void)snprintf(line, sizeof(line), "filling in parms for %s", p->name);
587     status(line);
588 
589     if (!p->ident)
590 	p->ident = genident(p->name);
591     if (!p->srcdir) {
592 	srcparent = dir_search(p->name);
593 	if (srcparent) {
594 	    (void)snprintf(path, sizeof(path), "%s/%s", srcparent, p->name);
595 	    if (is_dir(path)) {
596 		if (path[0] == '/') {
597                     if ((p->srcdir = strdup(path)) == NULL)
598 			out_of_memory();
599 		} else {
600 		    char tmppath[MAXPATHLEN];
601 		    if (topdir[0] == '\0')
602 			(void)estrlcpy(tmppath, curdir, sizeof(tmppath));
603 		    else
604 			(void)estrlcpy(tmppath, topdir, sizeof(tmppath));
605 		    (void)estrlcat(tmppath, "/", sizeof(tmppath));
606 		    (void)estrlcat(tmppath, path, sizeof(tmppath));
607 		    if ((p->srcdir = strdup(tmppath)) == NULL)
608 			out_of_memory();
609 		}
610 	    }
611 	}
612     }
613 
614     if (!p->srcdir && verbose)
615 	fprintf(stderr, "%s: %s: warning: could not find source directory.\n",
616 		infilename, p->name);
617 
618     if (!p->objdir && p->srcdir && useobjs) {
619 	if (makeobjdirprefix) {
620 	    (void)snprintf(path, sizeof(path), "%s/%s", makeobjdirprefix, p->srcdir);
621 	    if (is_dir(path))
622 		p->objdir = strdup(path);
623 	}
624 	if (!p->objdir) {
625 	    (void)snprintf(path, sizeof(path), "%s/obj.%s", p->srcdir, machine);
626 	    if (is_dir(path))
627 		p->objdir = strdup(path);
628 	}
629 	if (!p->objdir) {
630 	    (void)snprintf(path, sizeof(path), "%s/obj", p->srcdir);
631 	    if (is_dir(path))
632 		p->objdir = strdup(path);
633 	}
634 	if (!p->objdir) {
635 	    p->objdir = p->srcdir;
636         }
637     }
638 
639     if (oneobj)
640 	return;
641 
642     if (p->srcdir)
643 	(void)snprintf(path, sizeof(path), "%s/Makefile", p->srcdir);
644     if (!p->objs && p->srcdir && is_nonempty_file(path))
645 	fillin_program_objs(p, p->srcdir);
646 
647     if (!p->objpaths && p->objs) {
648 	char *objdir;
649 	if (p->objdir && useobjs)
650 	    objdir = p->objdir;
651 	else
652 	    objdir = p->ident;
653 	for (s = p->objs; s != NULL; s = s->next) {
654 	    (void)snprintf(line, sizeof(line), "%s/%s", objdir, s->str);
655 	    add_string(&p->objpaths, line);
656 	}
657     }
658 
659     if (!p->objs && verbose)
660 	fprintf(stderr, "%s: %s: warning: could not find any .o files.\n",
661 		infilename, p->name);
662 
663     if (!p->objpaths) {
664 	fprintf(stderr,
665 		"%s: %s: error: no objpaths specified or calculated.\n",
666 		infilename, p->name);
667 	p->goterror = goterror = 1;
668     }
669 }
670 
671 static void
672 fillin_program_objs(prog_t *p, char *dirpath)
673 {
674     char *obj, *cp;
675     int rc;
676     int fd;
677     FILE *f;
678     char tempfname[MAXPATHLEN];
679 
680     /* discover the objs from the srcdir Makefile */
681 
682     (void)snprintf(tempfname, sizeof(tempfname), "/tmp/%sXXXXXX", confname);
683     if ((fd = mkstemp(tempfname)) < 0) {
684 	perror(tempfname);
685 	exit(1);
686     }
687 
688     if ((f = fdopen(fd, "w")) == NULL) {
689 	perror(tempfname);
690 	goterror = 1;
691 	return;
692     }
693 
694     fprintf(f, ".include \"${.CURDIR}/Makefile\"\n");
695     fprintf(f, ".if defined(PROG)\n");
696     fprintf(f, "OBJS?= ${PROG}.o\n");
697     fprintf(f, ".endif\n");
698     fprintf(f, "crunchgen_objs:\n\t@echo 'OBJS= '${OBJS}\n");
699     fclose(f);
700 
701     (void)snprintf(line, sizeof(line),
702 	"cd %s && %s -B -f %s %s CRUNCHEDPROG=1 crunchgen_objs 2>&1", dirpath,
703 	makebin, tempfname, makeflags);
704     if ((f = popen(line, "r")) == NULL) {
705 	perror("submake pipe");
706 	goterror = 1;
707 	unlink(tempfname);
708 	return;
709     }
710 
711     while (fgets(line, MAXLINELEN, f)) {
712 	if (strncmp(line, "OBJS= ", 6)) {
713 	    if (strcmp(line,
714 	   	"sh: warning: running as root with dot in PATH\n") == 0)
715 		    continue;
716 	    fprintf(stderr, "make error: %s", line);
717 	    goterror = 1;
718 	    continue;
719 	}
720 	cp = line + 6;
721 	while (isspace((unsigned char)*cp))
722 	    cp++;
723 	while (*cp) {
724 	    obj = cp;
725 	    while (*cp && !isspace((unsigned char)*cp))
726 		cp++;
727 	    if (*cp)
728 		*cp++ = '\0';
729 	    add_string(&p->objs, obj);
730 	    while (isspace((unsigned char)*cp))
731 		cp++;
732 	}
733     }
734     if ((rc=pclose(f)) != 0) {
735 	fprintf(stderr, "make error: make returned %d\n", rc);
736 	goterror = 1;
737     }
738     unlink(tempfname);
739 }
740 
741 static void
742 remove_error_progs(void)
743 {
744     prog_t *p1, *p2;
745 
746     p1 = NULL; p2 = progs;
747     while (p2 != NULL) {
748 	if (!p2->goterror)
749 	    p1 = p2, p2 = p2->next;
750 	else {
751 	    /* delete it from linked list */
752 	    fprintf(stderr, "%s: %s: ignoring program because of errors.\n",
753 		    infilename, p2->name);
754 	    if (p1)
755 		p1->next = p2->next;
756 	    else
757 		progs = p2->next;
758 	    p2 = p2->next;
759 	}
760     }
761 }
762 
763 static void
764 gen_specials_cache(void)
765 {
766     FILE *cachef;
767     prog_t *p;
768 
769     (void)snprintf(line, sizeof(line), "generating %s", cachename);
770     status(line);
771 
772     if ((cachef = fopen(cachename, "w")) == NULL) {
773 	perror(cachename);
774 	goterror = 1;
775 	return;
776     }
777 
778     fprintf(cachef, "# %s - parm cache generated from %s by crunchgen %s\n\n",
779 	    cachename, infilename, CRUNCH_VERSION);
780 
781     for (p = progs; p != NULL; p = p->next) {
782 	fprintf(cachef, "\n");
783 	if (p->srcdir)
784 	    fprintf(cachef, "special %s srcdir %s\n", p->name, p->srcdir);
785 	if (p->objdir && useobjs)
786 	    fprintf(cachef, "special %s objdir %s\n", p->name, p->objdir);
787 	if (p->objs) {
788 	    fprintf(cachef, "special %s objs", p->name);
789 	    output_strlst(cachef, p->objs);
790 	}
791 	if (p->objpaths) {
792 	    fprintf(cachef, "special %s objpaths", p->name);
793 	    output_strlst(cachef, p->objpaths);
794 	}
795     }
796     fclose(cachef);
797 }
798 
799 
800 static void
801 gen_output_makefile(void)
802 {
803     prog_t *p;
804     FILE *outmk;
805 
806     (void)snprintf(line, sizeof(line), "generating %s", outmkname);
807     status(line);
808 
809     if ((outmk = fopen(outmkname, "w")) == NULL) {
810 	perror(outmkname);
811 	goterror = 1;
812 	return;
813     }
814 
815     fprintf(outmk, "# %s - generated from %s by crunchgen %s\n\n",
816 	    outmkname, infilename, CRUNCH_VERSION);
817 
818     top_makefile_rules(outmk);
819 
820     for (p = progs; p != NULL; p = p->next)
821 	prog_makefile_rules(outmk, p);
822 
823     fprintf(outmk, "\n.include <bsd.prog.mk>\n");
824     fprintf(outmk, "\n# ========\n");
825 
826     bottom_makefile_rules(outmk);
827 
828     fclose(outmk);
829 }
830 
831 
832 static void
833 gen_output_cfile(void)
834 {
835     char **cp;
836     FILE *outcf;
837     prog_t *p;
838     strlst_t *s;
839 
840     (void)snprintf(line, sizeof(line), "generating %s", outcfname);
841     status(line);
842 
843     if ((outcf = fopen(outcfname, "w")) == NULL) {
844 	perror(outcfname);
845 	goterror = 1;
846 	return;
847     }
848 
849     fprintf(outcf,
850 	  "/* %s - generated from %s by crunchgen %s */\n",
851 	    outcfname, infilename, CRUNCH_VERSION);
852 
853     fprintf(outcf, "#define EXECNAME \"%s\"\n", execfname);
854     for (cp = crunched_skel; *cp != NULL; cp++)
855 	fprintf(outcf, "%s\n", *cp);
856 
857     for (p = progs; p != NULL; p = p->next)
858 	fprintf(outcf, "extern int _crunched_%s_stub(int, char **, char **);\n",
859 	    p->ident);
860 
861     fprintf(outcf, "\nstatic const struct stub entry_points[] = {\n");
862     for (p = progs; p != NULL; p = p->next) {
863 	fprintf(outcf, "\t{ \"%s\", _crunched_%s_stub },\n",
864 		p->name, p->ident);
865 	for (s = p->links; s != NULL; s = s->next)
866 	    fprintf(outcf, "\t{ \"%s\", _crunched_%s_stub },\n",
867 		    s->str, p->ident);
868     }
869 
870     fprintf(outcf, "\t{ EXECNAME, crunched_main },\n");
871     fprintf(outcf, "\t{ NULL, NULL }\n};\n");
872     fclose(outcf);
873 }
874 
875 
876 static char *
877 genident(char *str)
878 {
879     char *n,*s,*d;
880 
881     /*
882      * generates a Makefile/C identifier from a program name, mapping '-' to
883      * '_' and ignoring all other non-identifier characters.  This leads to
884      * programs named "foo.bar" and "foobar" to map to the same identifier.
885      */
886 
887     if ((n = strdup(str)) == NULL)
888 	return NULL;
889     for (d = s = n; *s != '\0'; s++) {
890 	if (*s == '-')
891 	    *d++ = '_';
892 	else
893 	    if (*s == '_' || isalnum((unsigned char)*s))
894 		*d++ = *s;
895     }
896     *d = '\0';
897     return n;
898 }
899 
900 
901 static char *
902 dir_search(char *progname)
903 {
904     char path[MAXPATHLEN];
905     strlst_t *dir;
906 
907     for (dir=srcdirs; dir != NULL; dir=dir->next) {
908 	(void)snprintf(path, sizeof(path), "%s/%s", dir->str, progname);
909 	if (is_dir(path))
910 	    return dir->str;
911     }
912     return NULL;
913 }
914 
915 
916 static void
917 top_makefile_rules(FILE *outmk)
918 {
919     prog_t *p;
920 
921     fprintf(outmk, "NOMAN=\n\n");
922 
923     fprintf(outmk, "DBG=%s\n", dbg);
924     fprintf(outmk, "MAKE?=make\n");
925 #ifdef NEW_TOOLCHAIN
926     fprintf(outmk, "OBJCOPY?=objcopy\n");
927     fprintf(outmk, "NM?=nm\n");
928     fprintf(outmk, "AWK?=awk\n");
929 #else
930     fprintf(outmk, "CRUNCHIDE?=crunchide\n");
931 #endif
932 
933     fprintf(outmk, "CRUNCHED_OBJS=");
934     for (p = progs; p != NULL; p = p->next)
935 	fprintf(outmk, " %s.cro", p->name);
936     fprintf(outmk, "\n");
937     fprintf(outmk, "DPADD+= ${CRUNCHED_OBJS}\n");
938     fprintf(outmk, "LDADD+= ${CRUNCHED_OBJS} ");
939     output_strlst(outmk, libs);
940     fprintf(outmk, "CRUNCHEDOBJSDIRS=");
941     for (p = progs; p != NULL; p = p->next)
942 	fprintf(outmk, " %s", p->ident);
943     fprintf(outmk, "\n\n");
944 
945     fprintf(outmk, "SUBMAKE_TARGETS=");
946     for (p = progs; p != NULL; p = p->next)
947 	fprintf(outmk, " %s_make", p->ident);
948     fprintf(outmk, "\n\n");
949 
950     fprintf(outmk, "LDSTATIC=-static\n\n");
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 .eh_frame -R .eh_frame_hdr -R .note -R .note.netbsd.mcmodel -R .note.netbsd.pax -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 static void
970 bottom_makefile_rules(FILE *outmk)
971 {
972 }
973 
974 
975 static void
976 prog_makefile_rules(FILE *outmk, prog_t *p)
977 {
978     strlst_t *lst;
979 
980     fprintf(outmk, "\n# -------- %s\n\n", p->name);
981 
982     fprintf(outmk, "%s_OBJPATHS=", p->ident);
983 #ifndef NEW_TOOLCHAIN
984     fprintf(outmk, " %s_stub.o", p->name);
985 #endif
986     if (p->objs)
987 	output_strlst(outmk, p->objpaths);
988     else
989 	fprintf(outmk, " %s/%s.ro\n", p->ident, p->name);
990 
991     if (p->srcdir && !useobjs) {
992 	fprintf(outmk, "%s_SRCDIR=%s\n", p->ident, p->srcdir);
993 	if (p->objs) {
994 	    fprintf(outmk, "%s_OBJS=", p->ident);
995 	    output_strlst(outmk, p->objs);
996 	}
997 	fprintf(outmk, "%s_make: %s .PHONY\n", p->ident, p->ident);
998 	fprintf(outmk, "\t( cd %s; printf '.PATH: ${%s_SRCDIR}\\n"
999 	    ".CURDIR:= ${%s_SRCDIR}\\n"
1000 	    ".include \"$${.CURDIR}/Makefile\"\\n",
1001 	    p->ident, p->ident, p->ident);
1002 	for (lst = vars; lst != NULL; lst = lst->next)
1003 	    fprintf(outmk, "%s\\n", lst->str);
1004 	fprintf(outmk, "'\\\n");
1005 #define MAKECMD \
1006     "\t| ${MAKE} -f- CRUNCHEDPROG=1 DBG=\"${DBG}\" LDSTATIC=\"${LDSTATIC}\" "
1007 	fprintf(outmk, MAKECMD "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, MAKECMD);
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 #ifdef NEW_TOOLCHAIN
1026     fprintf(outmk, "%s:\n\t mkdir %s\n", p->ident, p->ident);
1027 #endif
1028     fprintf(outmk, "%s.cro: %s .WAIT ${%s_OBJPATHS}\n",
1029 	p->name, p->ident, p->ident);
1030 
1031 #ifdef NEW_TOOLCHAIN
1032     if (p->objs)
1033 	fprintf(outmk, "\t${LD} -r -o %s/%s.ro $(%s_OBJPATHS)\n",
1034 		p->ident, p->name, p->ident);
1035     /* Use one awk command.... */
1036     fprintf(outmk, "\t${NM} -ng %s/%s.ro | ${AWK} '/^ *U / { next };",
1037 	    p->ident, p->name);
1038     fprintf(outmk, " /^[0-9a-fA-F]+ C/ { next };");
1039     for (lst = p->keepsymbols; lst != NULL; lst = lst->next)
1040 	fprintf(outmk, " / %s$$/ { next };", lst->str);
1041     fprintf(outmk, " / main$$/ { print \"main _crunched_%s_stub\"; next };",
1042 	    p->ident);
1043     /* gdb thinks these are C++ and ignores everthing after the first $$. */
1044     fprintf(outmk, " { print $$3 \" \" $$3 \"$$$$from$$$$%s\" }' "
1045 	    "> %s.cro.syms\n", p->name, p->name);
1046     fprintf(outmk, "\t${OBJCOPY} --redefine-syms %s.cro.syms ", p->name);
1047     fprintf(outmk, "%s/%s.ro %s.cro\n", p->ident, p->name, p->name);
1048 #else
1049     fprintf(outmk, "\t${LD} -dc -r -o %s.cro $(%s_OBJPATHS)\n",
1050 		p->name, p->ident);
1051     fprintf(outmk, "\t${CRUNCHIDE} -k _crunched_%s_stub ", p->ident);
1052     for (lst = p->keepsymbols; lst != NULL; lst = lst->next)
1053 	fprintf(outmk, "-k %s ", lst->str);
1054     fprintf(outmk, "%s.cro\n", p->name);
1055     fprintf(outmk, "%s_stub.c:\n", p->name);
1056     fprintf(outmk, "\techo \""
1057 	           "int _crunched_%s_stub(int argc, char **argv, char **envp)"
1058 	           "{return main(argc,argv,envp);}\" >%s_stub.c\n",
1059 	    p->ident, p->name);
1060 #endif
1061 }
1062 
1063 static void
1064 output_strlst(FILE *outf, strlst_t *lst)
1065 {
1066     for (; lst != NULL; lst = lst->next)
1067 	fprintf(outf, " %s", lst->str);
1068     fprintf(outf, "\n");
1069 }
1070 
1071 
1072 /*
1073  * ========================================================================
1074  * general library routines
1075  *
1076  */
1077 
1078 static void
1079 status(const char *str)
1080 {
1081     static int lastlen = 0;
1082     int len, spaces;
1083 
1084     if (!verbose)
1085 	return;
1086 
1087     len = strlen(str);
1088     spaces = lastlen - len;
1089     if (spaces < 1)
1090 	spaces = 1;
1091 
1092     fprintf(stderr, " [%s]%*.*s\r", str, spaces, spaces, " ");
1093     fflush(stderr);
1094     lastlen = len;
1095 }
1096 
1097 
1098 static void
1099 out_of_memory(void)
1100 {
1101     fprintf(stderr, "%s: %d: out of memory, stopping.\n", infilename, linenum);
1102     exit(1);
1103 }
1104 
1105 
1106 static void
1107 add_string(strlst_t **listp, char *str)
1108 {
1109     strlst_t *p1, *p2;
1110 
1111     /* add to end, but be smart about dups */
1112 
1113     for (p1 = NULL, p2 = *listp; p2 != NULL; p1 = p2, p2 = p2->next)
1114 	if (!strcmp(p2->str, str))
1115 	    return;
1116 
1117     p2 = malloc(sizeof(strlst_t));
1118     if (p2)
1119 	p2->str = strdup(str);
1120     if (!p2 || !p2->str)
1121 	out_of_memory();
1122 
1123     p2->next = NULL;
1124     if (p1 == NULL)
1125 	*listp = p2;
1126     else
1127 	p1->next = p2;
1128 }
1129 
1130 
1131 static int
1132 is_dir(const char *pathname)
1133 {
1134     struct stat buf;
1135 
1136     if (stat(pathname, &buf) == -1)
1137 	return 0;
1138     return S_ISDIR(buf.st_mode);
1139 }
1140 
1141 static int
1142 is_nonempty_file(const char *pathname)
1143 {
1144     struct stat buf;
1145 
1146     if (stat(pathname, &buf) == -1)
1147 	return 0;
1148 
1149     return S_ISREG(buf.st_mode) && buf.st_size > 0;
1150 }
1151