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