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