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