Home | History | Annotate | Line # | Download | only in crunchgen
crunchgen.c revision 1.39
      1 /*	$NetBSD: crunchgen.c,v 1.39 2002/07/09 12:49:10 pooka 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 #include <sys/cdefs.h>
     35 #if defined(__RCSID) && !defined(lint)
     36 __RCSID("$NetBSD: crunchgen.c,v 1.39 2002/07/09 12:49:10 pooka Exp $");
     37 #endif
     38 
     39 #if HAVE_CONFIG_H
     40 #include "config.h"
     41 #endif
     42 
     43 #include <stdlib.h>
     44 #include <unistd.h>
     45 #include <stdio.h>
     46 #include <ctype.h>
     47 #include <string.h>
     48 
     49 #include <sys/types.h>
     50 #include <sys/stat.h>
     51 #include <sys/param.h>
     52 #include <sys/utsname.h>
     53 
     54 #define CRUNCH_VERSION	"0.2"
     55 
     56 #define MAXLINELEN	16384
     57 #define MAXFIELDS 	 2048
     58 
     59 
     60 /* internal representation of conf file: */
     61 
     62 /* simple lists of strings suffice for most parms */
     63 
     64 typedef struct strlst {
     65     struct strlst *next;
     66     char *str;
     67 } strlst_t;
     68 
     69 /* progs have structure, each field can be set with "special" or calculated */
     70 
     71 typedef struct prog {
     72     struct prog *next;
     73     char *name, *ident;
     74     char *srcdir, *objdir;
     75     strlst_t *objs, *objpaths;
     76     strlst_t *links, *keepsymbols;
     77     int goterror;
     78 } prog_t;
     79 
     80 
     81 /* global state */
     82 
     83 strlst_t *srcdirs = NULL;
     84 strlst_t *libs    = NULL;
     85 prog_t   *progs   = NULL;
     86 
     87 char line[MAXLINELEN];
     88 
     89 char confname[MAXPATHLEN], infilename[MAXPATHLEN];
     90 char outmkname[MAXPATHLEN], outcfname[MAXPATHLEN], execfname[MAXPATHLEN];
     91 char cachename[MAXPATHLEN], curfilename[MAXPATHLEN];
     92 char topdir[MAXPATHLEN];
     93 char libdir[MAXPATHLEN] = "/usr/lib";
     94 char dbg[MAXPATHLEN] = "-Os";
     95 int linenum = -1;
     96 int goterror = 0;
     97 
     98 char *pname = "crunchgen";
     99 
    100 int verbose, readcache, useobjs;	/* options */
    101 int reading_cache;
    102 char *machine;
    103 char *makeobjdirprefix;
    104 char *makebin;
    105 char *makeflags;
    106 
    107 /* general library routines */
    108 
    109 void status(char *str);
    110 void out_of_memory(void);
    111 void add_string(strlst_t **listp, char *str);
    112 int is_dir(char *pathname);
    113 int is_nonempty_file(char *pathname);
    114 
    115 /* helper routines for main() */
    116 
    117 void usage(void);
    118 void parse_conf_file(void);
    119 void gen_outputs(void);
    120 
    121 extern char *crunched_skel[];
    122 
    123 int main(int argc, char **argv)
    124 {
    125     char *p;
    126     int optc;
    127 
    128     if ((makebin = getenv("MAKE")) == NULL)
    129 	makebin = strdup("make");
    130 
    131     if ((makeflags = getenv("MAKEFLAGS")) == NULL)
    132 	makeflags = strdup("");
    133 
    134     if ((machine = getenv("MACHINE")) == NULL) {
    135 	struct utsname utsname;
    136 
    137 	if (uname(&utsname) == -1) {
    138 	    perror("uname");
    139 	    exit(1);
    140 	}
    141 	machine = utsname.machine;
    142     }
    143     makeobjdirprefix = getenv("MAKEOBJDIRPREFIX");
    144     verbose = 1;
    145     readcache = 1;
    146     useobjs = 0;
    147     *outmkname = *outcfname = *execfname = '\0';
    148 
    149     if(argc > 0) pname = argv[0];
    150 
    151     while((optc = getopt(argc, argv, "m:c:d:e:foqD:L:")) != -1) {
    152 	switch(optc) {
    153 	case 'f':	readcache = 0; break;
    154 	case 'q':	verbose = 0; break;
    155 	case 'o':       useobjs = 1; break;
    156 
    157 	case 'm':	strcpy(outmkname, optarg); break;
    158 	case 'c':	strcpy(outcfname, optarg); break;
    159 	case 'e':	strcpy(execfname, optarg); break;
    160 	case 'd':       strcpy(dbg, optarg); break;
    161 
    162 	case 'D':	strcpy(topdir, optarg); break;
    163 	case 'L':	strcpy(libdir, optarg); break;
    164 
    165 	case '?':
    166 	default:	usage();
    167 	}
    168     }
    169 
    170     argc -= optind;
    171     argv += optind;
    172 
    173     if(argc != 1) usage();
    174 
    175     /*
    176      * generate filenames
    177      */
    178 
    179     strcpy(infilename, argv[0]);
    180 
    181     /* confname = `basename infilename .conf` */
    182 
    183     if((p=strrchr(infilename, '/')) != NULL) strcpy(confname, p+1);
    184     else strcpy(confname, infilename);
    185     if((p=strrchr(confname, '.')) != NULL && !strcmp(p, ".conf")) *p = '\0';
    186 
    187     if (!*outmkname)
    188 	(void)snprintf(outmkname, sizeof(outmkname), "%s.mk", confname);
    189     if (!*outcfname)
    190 	(void)snprintf(outcfname, sizeof(outcfname), "%s.c", confname);
    191     if (!*execfname)
    192 	(void)snprintf(execfname, sizeof(execfname), "%s", confname);
    193 
    194     (void)snprintf(cachename, sizeof(cachename), "%s.cache", confname);
    195 
    196     parse_conf_file();
    197     gen_outputs();
    198 
    199     exit(goterror);
    200 }
    201 
    202 
    203 void usage(void)
    204 {
    205     fprintf(stderr,
    206 	"%s [-foq] [-m <makefile>] [-c <c file>] [-e <exec file>]\n"
    207 	"\t  [-d <buildopts] [-D <src root>] [-L <lib dir>] <conffile>\n",
    208 	    pname);
    209     exit(1);
    210 }
    211 
    212 
    213 /*
    214  * ========================================================================
    215  * parse_conf_file subsystem
    216  *
    217  */
    218 
    219 /* helper routines for parse_conf_file */
    220 
    221 void parse_one_file(char *filename);
    222 void parse_line(char *line, int *fc, char **fv, int nf);
    223 void add_srcdirs(int argc, char **argv);
    224 void add_progs(int argc, char **argv);
    225 void add_link(int argc, char **argv);
    226 void add_libs(int argc, char **argv);
    227 void add_special(int argc, char **argv);
    228 
    229 prog_t *find_prog(char *str);
    230 void add_prog(char *progname);
    231 
    232 
    233 void parse_conf_file(void)
    234 {
    235     if(!is_nonempty_file(infilename)) {
    236 	fprintf(stderr, "%s: fatal: input file \"%s\" not found.\n",
    237 		pname, infilename);
    238 	exit(1);
    239     }
    240     parse_one_file(infilename);
    241     if(readcache && is_nonempty_file(cachename)) {
    242 	reading_cache = 1;
    243 	parse_one_file(cachename);
    244     }
    245 }
    246 
    247 
    248 void parse_one_file(char *filename)
    249 {
    250     char *fieldv[MAXFIELDS];
    251     int fieldc;
    252     void (*f)(int c, char **v);
    253     FILE *cf;
    254 
    255     (void)snprintf(line, sizeof(line), "reading %s", filename);
    256     status(line);
    257     strcpy(curfilename, filename);
    258 
    259     if((cf = fopen(curfilename, "r")) == NULL) {
    260 	perror(curfilename);
    261 	goterror = 1;
    262 	return;
    263     }
    264 
    265     linenum = 0;
    266     while(fgets(line, MAXLINELEN, cf) != NULL) {
    267 	linenum++;
    268 	parse_line(line, &fieldc, fieldv, MAXFIELDS);
    269 	if(fieldc < 1) continue;
    270 	if(!strcmp(fieldv[0], "srcdirs"))	f = add_srcdirs;
    271 	else if(!strcmp(fieldv[0], "progs"))    f = add_progs;
    272 	else if(!strcmp(fieldv[0], "ln"))	f = add_link;
    273 	else if(!strcmp(fieldv[0], "libs"))	f = add_libs;
    274 	else if(!strcmp(fieldv[0], "special"))	f = add_special;
    275 	else {
    276 	    fprintf(stderr, "%s:%d: skipping unknown command `%s'.\n",
    277 		    curfilename, linenum, fieldv[0]);
    278 	    goterror = 1;
    279 	    continue;
    280 	}
    281 	if(fieldc < 2) {
    282 	    fprintf(stderr,
    283 		    "%s:%d: %s command needs at least 1 argument, skipping.\n",
    284 		    curfilename, linenum, fieldv[0]);
    285 	    goterror = 1;
    286 	    continue;
    287 	}
    288 	f(fieldc, fieldv);
    289     }
    290 
    291     if(ferror(cf)) {
    292 	perror(curfilename);
    293 	goterror = 1;
    294     }
    295     fclose(cf);
    296 }
    297 
    298 
    299 void parse_line(char *line, int *fc, char **fv, int nf)
    300 {
    301     char *p;
    302 
    303     p = line;
    304     *fc = 0;
    305     while(1) {
    306 	while(isspace(*p)) p++;
    307 	if(*p == '\0' || *p == '#') break;
    308 
    309 	if(*fc < nf) fv[(*fc)++] = p;
    310 	while(*p && !isspace(*p) && *p != '#') p++;
    311 	if(*p == '\0' || *p == '#') break;
    312 	*p++ = '\0';
    313     }
    314     if(*p) *p = '\0';		/* needed for '#' case */
    315 }
    316 
    317 
    318 void add_srcdirs(int argc, char **argv)
    319 {
    320     int i;
    321     char tmppath[MAXPATHLEN];
    322 
    323     for(i=1;i<argc;i++) {
    324 	if (argv[i][0] == '/' || topdir[0] == '\0')
    325 		strcpy(tmppath, argv[i]);
    326 	else {
    327 		strcpy(tmppath, topdir);
    328 		strcat(tmppath, "/");
    329 		strcat(tmppath, argv[i]);
    330 	}
    331 	if(is_dir(tmppath))
    332 	    add_string(&srcdirs, tmppath);
    333 	else {
    334 	    fprintf(stderr, "%s:%d: `%s' is not a directory, skipping it.\n",
    335 		    curfilename, linenum, tmppath);
    336 	    goterror = 1;
    337 	}
    338     }
    339 }
    340 
    341 
    342 void add_progs(int argc, char **argv)
    343 {
    344     int i;
    345 
    346     for(i=1;i<argc;i++)
    347 	add_prog(argv[i]);
    348 }
    349 
    350 
    351 void add_prog(char *progname)
    352 {
    353     prog_t *p1, *p2;
    354 
    355     /* add to end, but be smart about dups */
    356 
    357     for(p1 = NULL, p2 = progs; p2 != NULL; p1 = p2, p2 = p2->next)
    358 	if(!strcmp(p2->name, progname)) return;
    359 
    360     p2 = malloc(sizeof(prog_t));
    361     if(p2) p2->name = strdup(progname);
    362     if(!p2 || !p2->name)
    363 	out_of_memory();
    364 
    365     p2->next = NULL;
    366     if(p1 == NULL) progs = p2;
    367     else p1->next = p2;
    368 
    369     p2->ident = p2->srcdir = p2->objdir = NULL;
    370     p2->objs = p2->objpaths = p2->links = p2->keepsymbols = NULL;
    371     p2->goterror = 0;
    372 }
    373 
    374 
    375 void add_link(int argc, char **argv)
    376 {
    377     int i;
    378     prog_t *p = find_prog(argv[1]);
    379 
    380     if(p == NULL) {
    381 	fprintf(stderr,
    382 		"%s:%d: no prog %s previously declared, skipping link.\n",
    383 		curfilename, linenum, argv[1]);
    384 	goterror = 1;
    385 	return;
    386     }
    387     for(i=2;i<argc;i++)
    388 	add_string(&p->links, argv[i]);
    389 }
    390 
    391 
    392 void add_libs(int argc, char **argv)
    393 {
    394     int i;
    395 
    396     for(i=1;i<argc;i++)
    397 	add_string(&libs, argv[i]);
    398 }
    399 
    400 
    401 void add_special(int argc, char **argv)
    402 {
    403     int i;
    404     prog_t *p = find_prog(argv[1]);
    405 
    406     if(p == NULL) {
    407 	if(reading_cache) return;
    408 	fprintf(stderr,
    409 		"%s:%d: no prog %s previously declared, skipping special.\n",
    410 		curfilename, linenum, argv[1]);
    411 	goterror = 1;
    412 	return;
    413     }
    414 
    415     if(!strcmp(argv[2], "ident")) {
    416 	if(argc != 4) goto argcount;
    417 	if((p->ident = strdup(argv[3])) == NULL)
    418 	    out_of_memory();
    419     }
    420     else if(!strcmp(argv[2], "srcdir")) {
    421 	if(argc != 4) goto argcount;
    422 	if (argv[3][0] == '/' || topdir[0] == '\0') {
    423 	    if((p->srcdir = strdup(argv[3])) == NULL)
    424 		out_of_memory();
    425 	} else {
    426 	    char tmppath[MAXPATHLEN];
    427 	    strcpy(tmppath, topdir);
    428 	    strcat(tmppath, "/");
    429 	    strcat(tmppath, argv[3]);
    430 	    if((p->srcdir = strdup(tmppath)) == NULL)
    431 		out_of_memory();
    432 	}
    433     }
    434     else if(!strcmp(argv[2], "objdir")) {
    435 	if(argc != 4) goto argcount;
    436 	if((p->objdir = strdup(argv[3])) == NULL)
    437 	    out_of_memory();
    438     }
    439     else if(!strcmp(argv[2], "objs")) {
    440 	p->objs = NULL;
    441 	for(i=3;i<argc;i++)
    442 	    add_string(&p->objs, argv[i]);
    443     }
    444     else if(!strcmp(argv[2], "objpaths")) {
    445 	p->objpaths = NULL;
    446 	for(i=3;i<argc;i++)
    447 	    add_string(&p->objpaths, argv[i]);
    448     }
    449     else if(!strcmp(argv[2], "keepsymbols")) {
    450 	p->keepsymbols = NULL;
    451 	for (i=3;i<argc;i++)
    452 	    add_string(&p->keepsymbols, argv[i]);
    453     }
    454     else {
    455 	fprintf(stderr, "%s:%d: bad parameter name `%s', skipping line.\n",
    456 		curfilename, linenum, argv[2]);
    457 	goterror = 1;
    458     }
    459     return;
    460 
    461 
    462  argcount:
    463     fprintf(stderr,
    464 	    "%s:%d: too %s arguments, expected \"special %s %s <string>\".\n",
    465 	    curfilename, linenum, argc < 4? "few" : "many", argv[1], argv[2]);
    466     goterror = 1;
    467 }
    468 
    469 
    470 prog_t *find_prog(char *str)
    471 {
    472     prog_t *p;
    473 
    474     for(p = progs; p != NULL; p = p->next)
    475 	if(!strcmp(p->name, str)) return p;
    476 
    477     return NULL;
    478 }
    479 
    480 
    481 /*
    482  * ========================================================================
    483  * gen_outputs subsystem
    484  *
    485  */
    486 
    487 /* helper subroutines */
    488 
    489 void remove_error_progs(void);
    490 void fillin_program(prog_t *p);
    491 void gen_specials_cache(void);
    492 void gen_output_makefile(void);
    493 void gen_output_cfile(void);
    494 
    495 void fillin_program_objs(prog_t *p, char *path);
    496 void top_makefile_rules(FILE *outmk);
    497 void prog_makefile_rules(FILE *outmk, prog_t *p);
    498 void output_strlst(FILE *outf, strlst_t *lst);
    499 char *genident(char *str);
    500 char *dir_search(char *progname);
    501 
    502 
    503 void gen_outputs(void)
    504 {
    505     prog_t *p;
    506 
    507     for(p = progs; p != NULL; p = p->next)
    508 	fillin_program(p);
    509 
    510     remove_error_progs();
    511     gen_specials_cache();
    512     gen_output_cfile();
    513     gen_output_makefile();
    514     status("");
    515     fprintf(stderr,
    516 	    "Run \"make -f %s objs exe\" to build crunched binary.\n",
    517 	    outmkname);
    518 }
    519 
    520 
    521 void fillin_program(prog_t *p)
    522 {
    523     char path[MAXPATHLEN];
    524     char *srcparent;
    525     strlst_t *s;
    526 
    527     (void)snprintf(line, sizeof(line), "filling in parms for %s", p->name);
    528     status(line);
    529 
    530     if(!p->ident)
    531 	p->ident = genident(p->name);
    532     if(!p->srcdir) {
    533 	srcparent = dir_search(p->name);
    534 	if(srcparent) {
    535 	    (void)snprintf(path, sizeof(path), "%s/%s", srcparent, p->name);
    536 	    if(is_dir(path))
    537 		p->srcdir = strdup(path);
    538 	}
    539     }
    540     if(!p->objdir && p->srcdir && useobjs) {
    541 	if (makeobjdirprefix) {
    542 	    (void)snprintf(path, sizeof(path), "%s/%s", makeobjdirprefix, p->srcdir);
    543 	    if (is_dir(path))
    544 		p->objdir = strdup(path);
    545 	}
    546 	if (!p->objdir) {
    547 	    (void)snprintf(path, sizeof(path), "%s/obj.%s", p->srcdir, machine);
    548 	    if (is_dir(path))
    549 		p->objdir = strdup(path);
    550 	}
    551 	if (!p->objdir) {
    552 	    (void)snprintf(path, sizeof(path), "%s/obj", p->srcdir);
    553 	    if(is_dir(path))
    554 		p->objdir = strdup(path);
    555 	}
    556 	if (!p->objdir) {
    557 	    p->objdir = p->srcdir;
    558         }
    559     }
    560 
    561     if(p->srcdir)
    562 	(void)snprintf(path, sizeof(path), "%s/Makefile", p->srcdir);
    563     if(!p->objs && p->srcdir && is_nonempty_file(path))
    564 	fillin_program_objs(p, p->srcdir);
    565 
    566     if(!p->objpaths && p->objs) {
    567 	if (p->objdir && useobjs) {
    568 	    for(s = p->objs; s != NULL; s = s->next) {
    569 		(void)snprintf(line, sizeof(line), "%s/%s", p->objdir, s->str);
    570 		add_string(&p->objpaths, line);
    571 	    }
    572 	} else {
    573 	    for(s = p->objs; s != NULL; s = s->next) {
    574 		(void)snprintf(line, sizeof(line), "%s/%s", p->ident, s->str);
    575 		add_string(&p->objpaths, line);
    576 	    }
    577 	}
    578     }
    579 
    580     if(!p->srcdir && verbose)
    581 	fprintf(stderr, "%s: %s: warning: could not find source directory.\n",
    582 		infilename, p->name);
    583     if(!p->objs && verbose)
    584 	fprintf(stderr, "%s: %s: warning: could not find any .o files.\n",
    585 		infilename, p->name);
    586 
    587     if(!p->objpaths) {
    588 	fprintf(stderr,
    589 		"%s: %s: error: no objpaths specified or calculated.\n",
    590 		infilename, p->name);
    591 	p->goterror = goterror = 1;
    592     }
    593 }
    594 
    595 void fillin_program_objs(prog_t *p, char *dirpath)
    596 {
    597     char *obj, *cp;
    598     int rc;
    599     int fd;
    600     FILE *f;
    601     char tempfname[MAXPATHLEN];
    602 
    603     /* discover the objs from the srcdir Makefile */
    604 
    605     (void)snprintf(tempfname, sizeof(tempfname), "/tmp/%sXXXXXX", confname);
    606     if((fd = mkstemp(tempfname)) < 0) {
    607 	perror(tempfname);
    608 	exit(1);
    609     }
    610 
    611     if((f = fdopen(fd, "w")) == NULL) {
    612 	perror(tempfname);
    613 	goterror = 1;
    614 	return;
    615     }
    616 
    617     fprintf(f, ".include \"${.CURDIR}/Makefile\"\n");
    618     fprintf(f, ".if defined(PROG)\n");
    619     fprintf(f, "OBJS?= ${PROG}.o\n");
    620     fprintf(f, ".endif\n");
    621     fprintf(f, "crunchgen_objs:\n\t@echo 'OBJS= '${OBJS}\n");
    622     fclose(f);
    623 
    624     (void)snprintf(line, sizeof(line),
    625 	"cd %s && %s -B CRUNCHEDPROG=1 -f %s %s crunchgen_objs 2>&1", dirpath,
    626 	makebin, tempfname, makeflags);
    627     if((f = popen(line, "r")) == NULL) {
    628 	perror("submake pipe");
    629 	goterror = 1;
    630 	unlink(tempfname);
    631 	return;
    632     }
    633 
    634     while(fgets(line, MAXLINELEN, f)) {
    635 	if(strncmp(line, "OBJS= ", 6)) {
    636 	    if (strcmp(line,
    637 	   	"sh: warning: running as root with dot in PATH\n") == 0)
    638 		    continue;
    639 	    fprintf(stderr, "make error: %s", line);
    640 	    goterror = 1;
    641 	    continue;
    642 	}
    643 	cp = line + 6;
    644 	while(isspace(*cp)) cp++;
    645 	while(*cp) {
    646 	    obj = cp;
    647 	    while(*cp && !isspace(*cp)) cp++;
    648 	    if(*cp) *cp++ = '\0';
    649 	    add_string(&p->objs, obj);
    650 	    while(isspace(*cp)) cp++;
    651 	}
    652     }
    653     if((rc=pclose(f)) != 0) {
    654 	fprintf(stderr, "make error: make returned %d\n", rc);
    655 	goterror = 1;
    656     }
    657     unlink(tempfname);
    658 }
    659 
    660 void remove_error_progs(void)
    661 {
    662     prog_t *p1, *p2;
    663 
    664     p1 = NULL; p2 = progs;
    665     while(p2 != NULL) {
    666 	if(!p2->goterror)
    667 	    p1 = p2, p2 = p2->next;
    668 	else {
    669 	    /* delete it from linked list */
    670 	    fprintf(stderr, "%s: %s: ignoring program because of errors.\n",
    671 		    infilename, p2->name);
    672 	    if(p1) p1->next = p2->next;
    673 	    else progs = p2->next;
    674 	    p2 = p2->next;
    675 	}
    676     }
    677 }
    678 
    679 void gen_specials_cache(void)
    680 {
    681     FILE *cachef;
    682     prog_t *p;
    683 
    684     (void)snprintf(line, sizeof(line), "generating %s", cachename);
    685     status(line);
    686 
    687     if((cachef = fopen(cachename, "w")) == NULL) {
    688 	perror(cachename);
    689 	goterror = 1;
    690 	return;
    691     }
    692 
    693     fprintf(cachef, "# %s - parm cache generated from %s by crunchgen %s\n\n",
    694 	    cachename, infilename, CRUNCH_VERSION);
    695 
    696     for(p = progs; p != NULL; p = p->next) {
    697 	fprintf(cachef, "\n");
    698 	if(p->srcdir)
    699 	    fprintf(cachef, "special %s srcdir %s\n", p->name, p->srcdir);
    700 	if(p->objdir && useobjs)
    701 	    fprintf(cachef, "special %s objdir %s\n", p->name, p->objdir);
    702 	if(p->objs) {
    703 	    fprintf(cachef, "special %s objs", p->name);
    704 	    output_strlst(cachef, p->objs);
    705 	}
    706 	fprintf(cachef, "special %s objpaths", p->name);
    707 	output_strlst(cachef, p->objpaths);
    708     }
    709     fclose(cachef);
    710 }
    711 
    712 
    713 void gen_output_makefile(void)
    714 {
    715     prog_t *p;
    716     FILE *outmk;
    717 
    718     (void)snprintf(line, sizeof(line), "generating %s", outmkname);
    719     status(line);
    720 
    721     if((outmk = fopen(outmkname, "w")) == NULL) {
    722 	perror(outmkname);
    723 	goterror = 1;
    724 	return;
    725     }
    726 
    727     fprintf(outmk, "# %s - generated from %s by crunchgen %s\n\n",
    728 	    outmkname, infilename, CRUNCH_VERSION);
    729 
    730     top_makefile_rules(outmk);
    731 
    732     for(p = progs; p != NULL; p = p->next)
    733 	prog_makefile_rules(outmk, p);
    734 
    735     fprintf(outmk, "\n.include <bsd.prog.mk>\n");
    736     fprintf(outmk, "\n# ========\n");
    737     fclose(outmk);
    738 }
    739 
    740 
    741 void gen_output_cfile(void)
    742 {
    743     char **cp;
    744     FILE *outcf;
    745     prog_t *p;
    746     strlst_t *s;
    747 
    748     (void)snprintf(line, sizeof(line), "generating %s", outcfname);
    749     status(line);
    750 
    751     if((outcf = fopen(outcfname, "w")) == NULL) {
    752 	perror(outcfname);
    753 	goterror = 1;
    754 	return;
    755     }
    756 
    757     fprintf(outcf,
    758 	  "/* %s - generated from %s by crunchgen %s */\n",
    759 	    outcfname, infilename, CRUNCH_VERSION);
    760 
    761     fprintf(outcf, "#define EXECNAME \"%s\"\n", execfname);
    762     for(cp = crunched_skel; *cp != NULL; cp++)
    763 	fprintf(outcf, "%s\n", *cp);
    764 
    765     for(p = progs; p != NULL; p = p->next)
    766 	fprintf(outcf, "extern int _crunched_%s_stub();\n", p->ident);
    767 
    768     fprintf(outcf, "\nstruct stub entry_points[] = {\n");
    769     for(p = progs; p != NULL; p = p->next) {
    770 	fprintf(outcf, "\t{ \"%s\", _crunched_%s_stub },\n",
    771 		p->name, p->ident);
    772 	for(s = p->links; s != NULL; s = s->next)
    773 	    fprintf(outcf, "\t{ \"%s\", _crunched_%s_stub },\n",
    774 		    s->str, p->ident);
    775     }
    776 
    777     fprintf(outcf, "\t{ EXECNAME, crunched_main },\n");
    778     fprintf(outcf, "\t{ NULL, NULL }\n};\n");
    779     fclose(outcf);
    780 }
    781 
    782 
    783 char *genident(char *str)
    784 {
    785     char *n,*s,*d;
    786 
    787     /*
    788      * generates a Makefile/C identifier from a program name, mapping '-' to
    789      * '_' and ignoring all other non-identifier characters.  This leads to
    790      * programs named "foo.bar" and "foobar" to map to the same identifier.
    791      */
    792 
    793     if((n = strdup(str)) == NULL)
    794 	return NULL;
    795     for(d = s = n; *s != '\0'; s++) {
    796 	if(*s == '-') *d++ = '_';
    797 	else if(*s == '_' || isalnum(*s)) *d++ = *s;
    798     }
    799     *d = '\0';
    800     return n;
    801 }
    802 
    803 
    804 char *dir_search(char *progname)
    805 {
    806     char path[MAXPATHLEN];
    807     strlst_t *dir;
    808 
    809     for(dir=srcdirs; dir != NULL; dir=dir->next) {
    810 	(void)snprintf(path, sizeof(path), "%s/%s", dir->str, progname);
    811 	if(is_dir(path)) return dir->str;
    812     }
    813     return NULL;
    814 }
    815 
    816 
    817 void top_makefile_rules(FILE *outmk)
    818 {
    819     prog_t *p;
    820 
    821     fprintf(outmk, "DBG=%s\n", dbg);
    822     fprintf(outmk, "STRIP?=strip\n");
    823     fprintf(outmk, "MAKE?=make\n");
    824 #ifdef NEW_TOOLCHAIN
    825     fprintf(outmk, "OBJCOPY?=objcopy\n");
    826 #else
    827     fprintf(outmk, "CRUNCHIDE?=crunchide\n");
    828 #endif
    829 
    830     fprintf(outmk, "CRUNCHED_OBJS=");
    831     for(p = progs; p != NULL; p = p->next)
    832 	fprintf(outmk, " %s.cro", p->name);
    833     fprintf(outmk, "\n");
    834     fprintf(outmk, "LDSTATIC=-static\n");
    835     fprintf(outmk, "DPADD+= ${CRUNCHED_OBJS}\n");
    836     fprintf(outmk, "LDADD+= ${CRUNCHED_OBJS} ");
    837     output_strlst(outmk, libs);
    838     fprintf(outmk, "CRUNCHEDOBJSDIRS=${CRUNCHED_OBJS:R}\n\n");
    839 
    840     fprintf(outmk, "SUBMAKE_TARGETS=");
    841     for(p = progs; p != NULL; p = p->next)
    842 	fprintf(outmk, " %s_make", p->ident);
    843     fprintf(outmk, "\n\n");
    844 
    845     fprintf(outmk, "PROG=%s\n", execfname);
    846     fprintf(outmk, "MKMAN=no\n\n");
    847 
    848     fprintf(outmk, "all: ${PROG}\n\t${STRIP} ${PROG}\n");
    849     fprintf(outmk, "objs: $(SUBMAKE_TARGETS)\n");
    850     fprintf(outmk, "exe: %s\n", execfname);
    851     fprintf(outmk, "clean:\n\trm -rf %s *.cro *.o *_stub.c ${CRUNCHEDOBJSDIRS}\n",
    852 	    execfname);
    853 }
    854 
    855 
    856 void prog_makefile_rules(FILE *outmk, prog_t *p)
    857 {
    858     strlst_t *lst;
    859 
    860     fprintf(outmk, "\n# -------- %s\n\n", p->name);
    861 
    862     fprintf(outmk,   "%s_OBJPATHS=", p->ident);
    863     output_strlst(outmk, p->objpaths);
    864 
    865     if(p->srcdir && p->objs && !useobjs) {
    866 	fprintf(outmk, "%s_SRCDIR=%s\n", p->ident, p->srcdir);
    867 	fprintf(outmk, "%s_OBJS=", p->ident);
    868 	output_strlst(outmk, p->objs);
    869 	fprintf(outmk, "%s_make: ${%s_OBJPATHS}\n", p->ident, p->ident);
    870 	fprintf(outmk, "${%s_OBJPATHS}: \n", p->ident);
    871 	fprintf(outmk, "\tif [ \\! -d %s ]; then mkdir %s; fi; cd %s; \\\n",
    872 	    p->ident, p->ident, p->ident);
    873 	fprintf(outmk, "\tprintf \".PATH: ${%s_SRCDIR}\\n.CURDIR:= ${%s_SRCDIR}\\n"
    874 	    ".include \\\"\\$${.CURDIR}/Makefile\\\"\\n\" \\\n", p->ident, p->ident);
    875 	fprintf(outmk, "\t| ${MAKE} CRUNCHEDPROG=1 DBG=\"${DBG}\" -f- depend ${%s_OBJS}\n\n",
    876 	    p->ident);
    877     }
    878     else
    879         fprintf(outmk, "%s_make:\n\t@echo \"** Using existing objs for %s\"\n\n",
    880 		p->ident, p->name);
    881 
    882 
    883     fprintf(outmk, "%s_stub.c:\n", p->name);
    884     fprintf(outmk, "\techo \""
    885 	           "int _crunched_%s_stub(int argc, char **argv, char **envp)"
    886 	           "{return main(argc,argv,envp);}\" >%s_stub.c\n",
    887 	    p->ident, p->name);
    888     if (useobjs)
    889 	    fprintf(outmk, "%s.cro: %s_stub.o\n",
    890 		p->name, p->name);
    891     else
    892 	    fprintf(outmk, "%s.cro: %s_stub.o ${%s_OBJPATHS}\n",
    893 		p->name, p->name, p->ident);
    894     fprintf(outmk, "\t${LD} -dc -r -o %s.cro %s_stub.o $(%s_OBJPATHS)\n",
    895 	    p->name, p->name, p->ident);
    896 #ifdef NEW_TOOLCHAIN
    897     fprintf(outmk, "\t${OBJCOPY} --keep-global-symbol _crunched_%s_stub ",
    898   	    p->ident);
    899     for (lst = p->keepsymbols; lst != NULL; lst = lst->next)
    900 	fprintf(outmk, "--keep-global-symbol %s ", lst->str);
    901 #else
    902     fprintf(outmk, "\t${CRUNCHIDE} -k _crunched_%s_stub ", p->ident);
    903     for (lst = p->keepsymbols; lst != NULL; lst = lst->next)
    904 	fprintf(outmk, "-k %s ", lst->str);
    905 #endif
    906     fprintf(outmk, "%s.cro\n", p->name);
    907 }
    908 
    909 void output_strlst(FILE *outf, strlst_t *lst)
    910 {
    911     for(; lst != NULL; lst = lst->next)
    912 	fprintf(outf, " %s", lst->str);
    913     fprintf(outf, "\n");
    914 }
    915 
    916 
    917 /*
    918  * ========================================================================
    919  * general library routines
    920  *
    921  */
    922 
    923 void status(char *str)
    924 {
    925     static int lastlen = 0;
    926     int len, spaces;
    927 
    928     if(!verbose) return;
    929 
    930     len = strlen(str);
    931     spaces = lastlen - len;
    932     if(spaces < 1) spaces = 1;
    933 
    934     fprintf(stderr, " [%s]%*.*s\r", str, spaces, spaces, " ");
    935     fflush(stderr);
    936     lastlen = len;
    937 }
    938 
    939 
    940 void out_of_memory(void)
    941 {
    942     fprintf(stderr, "%s: %d: out of memory, stopping.\n", infilename, linenum);
    943     exit(1);
    944 }
    945 
    946 
    947 void add_string(strlst_t **listp, char *str)
    948 {
    949     strlst_t *p1, *p2;
    950 
    951     /* add to end, but be smart about dups */
    952 
    953     for(p1 = NULL, p2 = *listp; p2 != NULL; p1 = p2, p2 = p2->next)
    954 	if(!strcmp(p2->str, str)) return;
    955 
    956     p2 = malloc(sizeof(strlst_t));
    957     if(p2) p2->str = strdup(str);
    958     if(!p2 || !p2->str)
    959 	out_of_memory();
    960 
    961     p2->next = NULL;
    962     if(p1 == NULL) *listp = p2;
    963     else p1->next = p2;
    964 }
    965 
    966 
    967 int is_dir(char *pathname)
    968 {
    969     struct stat buf;
    970 
    971     if(stat(pathname, &buf) == -1)
    972 	return 0;
    973     return S_ISDIR(buf.st_mode);
    974 }
    975 
    976 int is_nonempty_file(char *pathname)
    977 {
    978     struct stat buf;
    979 
    980     if(stat(pathname, &buf) == -1)
    981 	return 0;
    982 
    983     return S_ISREG(buf.st_mode) && buf.st_size > 0;
    984 }
    985