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