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