1/*	$NetBSD: mkmakefile.c,v 1.73 2024/04/05 00:43:42 riastradh Exp $	*/
2
3/*
4 * Copyright (c) 1992, 1993
5 *	The Regents of the University of California.  All rights reserved.
6 *
7 * This software was developed by the Computer Systems Engineering group
8 * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
9 * contributed to Berkeley.
10 *
11 * All advertising materials mentioning features or use of this software
12 * must display the following acknowledgement:
13 *	This product includes software developed by the University of
14 *	California, Lawrence Berkeley Laboratories.
15 *
16 * Redistribution and use in source and binary forms, with or without
17 * modification, are permitted provided that the following conditions
18 * are met:
19 * 1. Redistributions of source code must retain the above copyright
20 *    notice, this list of conditions and the following disclaimer.
21 * 2. Redistributions in binary form must reproduce the above copyright
22 *    notice, this list of conditions and the following disclaimer in the
23 *    documentation and/or other materials provided with the distribution.
24 * 3. Neither the name of the University nor the names of its contributors
25 *    may be used to endorse or promote products derived from this software
26 *    without specific prior written permission.
27 *
28 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
29 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
30 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
31 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
32 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
33 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
34 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
35 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
36 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
37 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
38 * SUCH DAMAGE.
39 *
40 *	from: @(#)mkmakefile.c	8.1 (Berkeley) 6/6/93
41 */
42
43#if HAVE_NBTOOL_CONFIG_H
44#include "nbtool_config.h"
45#endif
46
47#include <sys/cdefs.h>
48__RCSID("$NetBSD: mkmakefile.c,v 1.73 2024/04/05 00:43:42 riastradh Exp $");
49
50#include <sys/param.h>
51#include <ctype.h>
52#include <errno.h>
53#include <stdio.h>
54#include <stdlib.h>
55#include <string.h>
56#include <err.h>
57#include <util.h>
58#include "defs.h"
59#include "sem.h"
60
61/*
62 * Make the Makefile.
63 */
64
65static void emitdefs(FILE *);
66static void emitallfiles(FILE *);
67
68static void emitofiles(FILE *);
69static void emitallkobjs(FILE *);
70static int emitallkobjscb(const char *, void *, void *);
71static void emitattrkobjs(FILE *);
72static int emitattrkobjscb(const char *, void *, void *);
73static void emitkobjs(FILE *);
74static void emitcfiles(FILE *);
75static void emitsfiles(FILE *);
76static void emitrules(FILE *);
77static void emitload(FILE *);
78static void emitincludes(FILE *);
79static void emitappmkoptions(FILE *);
80static void emitmkoption(FILE *, const char *, const struct nvlist *);
81static void emitsubs(FILE *, const char *, const char *, int);
82static int  selectopt(const char *, void *);
83
84int has_build_kernel;
85
86int
87mkmakefile(void)
88{
89	FILE *ifp, *ofp;
90	int lineno;
91	void (*fn)(FILE *);
92	char line[BUFSIZ], ifname[200];
93
94	/*
95	 * Check if conf/Makefile.kern.inc defines "build_kernel".
96	 *
97	 * (This is usually done by checking "version" in sys/conf/files;
98	 * unfortunately the "build_kernel" change done around 2014 Aug didn't
99	 * bump that version.  Thus this hack.)
100	 */
101	(void)snprintf(ifname, sizeof(ifname), "%s/conf/Makefile.kern.inc",
102	    srcdir);
103	if ((ifp = fopen(ifname, "r")) == NULL) {
104		warn("cannot read %s", ifname);
105		goto bad2;
106	}
107	while (fgets(line, sizeof(line), ifp) != NULL) {
108		if (strncmp(line, "build_kernel:", 13) == 0) {
109			has_build_kernel = 1;
110			break;
111		}
112	}
113	(void)fclose(ifp);
114
115	/*
116	 * Try a makefile for the port first.
117	 */
118	(void)snprintf(ifname, sizeof(ifname), "%s/arch/%s/conf/Makefile.%s",
119	    srcdir, machine, machine);
120	if ((ifp = fopen(ifname, "r")) == NULL) {
121		/*
122		 * Try a makefile for the architecture second.
123		 */
124		(void)snprintf(ifname, sizeof(ifname),
125		    "%s/arch/%s/conf/Makefile.%s",
126		    srcdir, machinearch, machinearch);
127		ifp = fopen(ifname, "r");
128	}
129	if (ifp == NULL) {
130		warn("cannot read %s", ifname);
131		goto bad2;
132	}
133
134	if ((ofp = fopen("Makefile.tmp", "w")) == NULL) {
135		warn("cannot write Makefile");
136		goto bad1;
137	}
138
139	emitdefs(ofp);
140
141	lineno = 0;
142	while (fgets(line, sizeof(line), ifp) != NULL) {
143		lineno++;
144		if ((version < 20090214 && line[0] != '%') || line[0] == '#') {
145			fputs(line, ofp);
146			continue;
147		}
148		if (strcmp(line, "%OBJS\n") == 0)
149			fn = Mflag ? emitkobjs : emitofiles;
150		else if (strcmp(line, "%CFILES\n") == 0)
151			fn = emitcfiles;
152		else if (strcmp(line, "%SFILES\n") == 0)
153			fn = emitsfiles;
154		else if (strcmp(line, "%RULES\n") == 0)
155			fn = emitrules;
156		else if (strcmp(line, "%LOAD\n") == 0)
157			fn = emitload;
158		else if (strcmp(line, "%INCLUDES\n") == 0)
159			fn = emitincludes;
160		else if (strcmp(line, "%MAKEOPTIONSAPPEND\n") == 0)
161			fn = emitappmkoptions;
162		else if (strncmp(line, "%VERSION ", sizeof("%VERSION ")-1) == 0) {
163			int newvers;
164			if (sscanf(line, "%%VERSION %d\n", &newvers) != 1) {
165				cfgxerror(ifname, lineno, "syntax error for "
166				    "%%VERSION");
167			} else
168				setversion(newvers);
169			continue;
170		} else {
171			if (version < 20090214)
172				cfgxerror(ifname, lineno,
173				    "unknown %% construct ignored: %s", line);
174			else
175				emitsubs(ofp, line, ifname, lineno);
176			continue;
177		}
178		(*fn)(ofp);
179	}
180
181	fflush(ofp);
182	if (ferror(ofp))
183		goto wrerror;
184
185	if (ferror(ifp)) {
186		warn("error reading %s (at line %d)", ifname, lineno);
187		goto bad;
188	}
189
190	if (fclose(ofp)) {
191		ofp = NULL;
192		goto wrerror;
193	}
194	(void)fclose(ifp);
195
196	if (moveifchanged("Makefile.tmp", "Makefile") != 0) {
197		warn("error renaming Makefile");
198		goto bad2;
199	}
200	return (0);
201
202 wrerror:
203	warn("error writing Makefile");
204 bad:
205	if (ofp != NULL)
206		(void)fclose(ofp);
207 bad1:
208	(void)fclose(ifp);
209	/* (void)unlink("Makefile.tmp"); */
210 bad2:
211	return (1);
212}
213
214static void
215emitmkoption(FILE *fp, const char *ass, const struct nvlist *nv)
216{
217	const char *p;
218
219	fprintf(fp, "%s%s", nv->nv_name, ass);
220	for (p = nv->nv_str; *p; p++) {
221		if (*p == '\n')
222			fputs(" \\", fp);
223		fputc(*p, fp);
224	}
225	fputc('\n', fp);
226}
227
228static void
229emitsubs(FILE *fp, const char *line, const char *file, int lineno)
230{
231	char *nextpct;
232	const char *optname;
233	struct nvlist *option;
234
235	while (*line != '\0') {
236		if (*line != '%') {
237			fputc(*line++, fp);
238			continue;
239		}
240
241		line++;
242		nextpct = strchr(line, '%');
243		if (nextpct == NULL) {
244			cfgxerror(file, lineno, "unbalanced %% or "
245			    "unknown construct");
246			return;
247		}
248		*nextpct = '\0';
249
250		if (*line == '\0')
251			fputc('%', fp);
252		else {
253			optname = intern(line);
254			if (!DEFINED_OPTION(optname)) {
255				cfgxerror(file, lineno, "unknown option %s",
256				    optname);
257				return;
258			}
259
260			if ((option = ht_lookup(opttab, optname)) == NULL)
261				option = ht_lookup(fsopttab, optname);
262			if (option != NULL)
263				fputs(option->nv_str ? option->nv_str : "1",
264				    fp);
265			/*
266			 * Otherwise it's not a selected option and we don't
267			 * output anything.
268			 */
269		}
270
271		line = nextpct + 1;
272	}
273}
274
275static void
276emitdefs(FILE *fp)
277{
278	struct defoptlist *dl;
279	struct nvlist *nv;
280
281	fprintf(fp, "KERNEL_BUILD=%s\n", conffile);
282	fputs("IDENT= \\\n", fp);
283	for (nv = options; nv != NULL; nv = nv->nv_next) {
284
285		/* Skip any options output to a header file */
286		if (DEFINED_OPTION(nv->nv_name))
287			continue;
288		const char *s = nv->nv_str;
289		fprintf(fp, "\t-D%s%s%s%s \\\n", nv->nv_name,
290		    s ? "=\"" : "",
291		    s ? s : "",
292		    s ? "\"" : "");
293	}
294	putc('\n', fp);
295	fprintf(fp, "MACHINE=%s\n", machine);
296
297	const char *subdir = "";
298	if (*srcdir != '/' && *srcdir != '.') {
299		/*
300		 * libkern and libcompat "Makefile.inc"s want relative S
301		 * specification to begin with '.'.
302		 */
303		subdir = "./";
304	}
305	fprintf(fp, "S=\t%s%s\n", subdir, srcdir);
306	if (Sflag) {
307		fprintf(fp, ".PATH: $S\n");
308		fprintf(fp, "___USE_SUFFIX_RULES___=1\n");
309	}
310	for (nv = mkoptions; nv != NULL; nv = nv->nv_next)
311		emitmkoption(fp, "=", nv);
312
313	/*
314	 * Go through the options again and emit Makefile variables
315	 * for those specified to get one.
316	 */
317	for (nv = options; nv != NULL; nv = nv->nv_next) {
318
319		dl = find_declared_option_option(nv->nv_name);
320		if (dl != NULL && dl->dl_mkvar) {
321			const char *s = nv->nv_str;
322			if (s == NULL) {
323				s = "1";
324			}
325			fprintf(fp, "KERNEL_OPT_%s=\"%s\"\n", nv->nv_name, s);
326		}
327	}
328}
329
330static void
331emitfile(FILE *fp, struct files *fi)
332{
333	const char *defprologue = "$S/";
334	const char *prologue, *prefix, *sep;
335
336	if (Sflag)
337		defprologue = "";
338	prologue = prefix = sep = "";
339	if (*fi->fi_path != '/') {
340		prologue = defprologue;
341		if (fi->fi_prefix != NULL) {
342			if (*fi->fi_prefix == '/')
343				prologue = "";
344			prefix = fi->fi_prefix;
345			sep = "/";
346		}
347	}
348	fprintf(fp, "%s%s%s%s", prologue, prefix, sep, fi->fi_path);
349}
350
351static void
352emitfilerel(FILE *fp, struct files *fi)
353{
354	const char *prefix, *sep;
355
356	prefix = sep = "";
357	if (*fi->fi_path != '/') {
358		if (fi->fi_prefix != NULL) {
359			prefix = fi->fi_prefix;
360			sep = "/";
361		}
362	}
363	fprintf(fp, "%s%s%s", prefix, sep, fi->fi_path);
364}
365
366static void
367emitofiles(FILE *fp)
368{
369
370	emitallfiles(fp);
371	fprintf(fp, "#%%OFILES\n");
372}
373
374static void
375emitkobjs(FILE *fp)
376{
377	emitallkobjs(fp);
378	emitattrkobjs(fp);
379}
380
381static int emitallkobjsweighcb(const char *name, void *v, void *arg);
382static void weighattr(struct attr *a);
383static int attrcmp(const void *l, const void *r);
384
385struct attr **attrbuf;
386size_t attridx;
387
388static void
389emitallkobjs(FILE *fp)
390{
391	size_t i;
392
393	attrbuf = emalloc(nattrs * sizeof(*attrbuf));
394
395	ht_enumerate(attrtab, emitallkobjsweighcb, NULL);
396	ht_enumerate(attrtab, emitallkobjscb, NULL);
397	qsort(attrbuf, attridx, sizeof(struct attr *), attrcmp);
398
399	fputs("OBJS= \\\n", fp);
400	for (i = 0; i < attridx; i++)
401		fprintf(fp, "\t%s.ko \\\n", attrbuf[i]->a_name);
402	putc('\n', fp);
403
404	free(attrbuf);
405}
406
407static int
408emitallkobjscb(const char *name, void *v, void *arg)
409{
410	struct attr *a = v;
411
412	if (ht_lookup(selecttab, name) == NULL)
413		return 0;
414	if (TAILQ_EMPTY(&a->a_files))
415		return 0;
416	a->a_idx = attridx;
417	attrbuf[attridx++] = a;
418	/* XXX nattrs tracking is not exact yet */
419	if (attridx == nattrs) {
420		nattrs *= 2;
421		attrbuf = erealloc(attrbuf, nattrs * sizeof(*attrbuf));
422	}
423	return 0;
424}
425
426static int
427emitallkobjsweighcb(const char *name, void *v, void *arg)
428{
429	struct attr *a = v;
430
431	weighattr(a);
432	return 0;
433}
434
435static void
436weighattr(struct attr *a)
437{
438	struct attrlist *al;
439
440	for (al = a->a_deps; al != NULL; al = al->al_next) {
441		weighattr(al->al_this);
442	}
443	a->a_weight++;
444}
445
446static int
447attrcmp(const void *l, const void *r)
448{
449	const struct attr * const *a = l, * const *b = r;
450	const int wa = (*a)->a_weight, wb = (*b)->a_weight;
451
452	/*
453	 * Higher-weight first; then, among equal weights, earlier
454	 * index first.
455	 */
456	if (wa > wb)
457		return -1;
458	else if (wa < wb)
459		return +1;
460	else if ((*a)->a_idx < (*b)->a_idx)
461		return -1;
462	else if ((*a)->a_idx > (*b)->a_idx)
463		return +1;
464	else
465		abort();	/* no ties possible */
466}
467
468static void
469emitattrkobjs(FILE *fp)
470{
471	extern struct	hashtab *attrtab;
472
473	ht_enumerate(attrtab, emitattrkobjscb, fp);
474}
475
476static int
477emitattrkobjscb(const char *name, void *v, void *arg)
478{
479	struct attr *a = v;
480	struct files *fi;
481	FILE *fp = arg;
482
483	if (ht_lookup(selecttab, name) == NULL)
484		return 0;
485	if (TAILQ_EMPTY(&a->a_files))
486		return 0;
487	fputc('\n', fp);
488	fprintf(fp, "# %s (%d)\n", name, a->a_weight);
489	fprintf(fp, "OBJS.%s= \\\n", name);
490	TAILQ_FOREACH(fi, &a->a_files, fi_anext) {
491		fprintf(fp, "\t%s.o \\\n", fi->fi_base);
492	}
493	fputc('\n', fp);
494	fprintf(fp, "%s.ko: ${OBJS.%s}\n", name, name);
495	fprintf(fp, "\t${LINK_O}\n");
496	return 0;
497}
498
499static void
500emitcfiles(FILE *fp)
501{
502
503	emitallfiles(fp);
504	fprintf(fp, "#%%CFILES\n");
505}
506
507static void
508emitsfiles(FILE *fp)
509{
510
511	emitallfiles(fp);
512	fprintf(fp, "#%%SFILES\n");
513}
514
515static void
516emitallfiles(FILE *fp)
517{
518	struct files *fi;
519	static int called;
520	int i;
521	int found = 0;
522
523	if (called++ != 0)
524		return;
525	for (i = 0; i < (int)nselfiles; i++) {
526		fi = selfiles[i];
527		if (found++ == 0)
528			fprintf(fp, "ALLFILES= \\\n");
529		putc('\t', fp);
530		emitfilerel(fp, fi);
531		fputs(" \\\n", fp);
532	}
533	fputc('\n', fp);
534}
535
536/*
537 * Emit the make-rules.
538 */
539static void
540emitrules(FILE *fp)
541{
542	struct files *fi;
543	int i;
544	int found = 0;
545
546	for (i = 0; i < (int)nselfiles; i++) {
547		fi = selfiles[i];
548		if (fi->fi_mkrule == NULL)
549			continue;
550		fprintf(fp, "%s.o: ", fi->fi_base);
551		emitfile(fp, fi);
552		putc('\n', fp);
553		fprintf(fp, "\t%s\n\n", fi->fi_mkrule);
554		found++;
555	}
556	if (found == 0)
557		fprintf(fp, "#%%RULES\n");
558}
559
560/*
561 * Emit the load commands.
562 *
563 * This function is not to be called `spurt'.
564 */
565static void
566emitload(FILE *fp)
567{
568	struct config *cf;
569	int found = 0;
570
571	/*
572	 * Generate the backward-compatible "build_kernel" rule if
573	 * sys/conf/Makefile.kern.inc doesn't define any (pre-2014 Aug).
574	 */
575	if (has_build_kernel == 0) {
576		fprintf(fp, "build_kernel: .USE\n"
577		    "\t${SYSTEM_LD_HEAD}\n"
578		    "\t${SYSTEM_LD}%s\n"
579		    "\t${SYSTEM_LD_TAIL}\n"
580		    "\n",
581		    Sflag ? "" : " swap${.TARGET}.o");
582	}
583	/*
584	 * Generate per-kernel rules.
585	 */
586	TAILQ_FOREACH(cf, &allcf, cf_next) {
587		char swapobj[100];
588
589		if (Sflag) {
590			swapobj[0] = '\0';
591		} else {
592			(void)snprintf(swapobj, sizeof(swapobj), " swap%s.o",
593	 		    cf->cf_name);
594		}
595		fprintf(fp, "KERNELS+=%s\n", cf->cf_name);
596		found = 1;
597	}
598	if (found == 0)
599		fprintf(fp, "#%%LOAD\n");
600}
601
602/*
603 * Emit include headers (for any prefixes encountered)
604 */
605static void
606emitincludes(FILE *fp)
607{
608	struct prefix *pf;
609
610	SLIST_FOREACH(pf, &allprefixes, pf_next) {
611		const char *prologue = (*pf->pf_prefix == '/') ? "" : "$S/";
612
613		fprintf(fp, "EXTRA_INCLUDES+=\t-I%s%s\n",
614		    prologue, pf->pf_prefix);
615	}
616}
617
618/*
619 * Emit all options included in a conditional expression
620 */
621static void
622emitopts(FILE *fp, struct condexpr *cond, int include)
623{
624
625	switch (cond->cx_type) {
626	case CX_ATOM:
627		if (include && selectopt(cond->cx_u.atom, NULL))
628			fprintf(fp, " %s", cond->cx_u.atom);
629		break;
630	case CX_NOT:
631		emitopts(fp, cond->cx_u.not, !include);
632		break;
633	case CX_AND:
634		emitopts(fp, cond->cx_u.and.left, include);
635		emitopts(fp, cond->cx_u.and.right, include);
636		break;
637	case CX_OR:
638		emitopts(fp, cond->cx_u.and.left, include);
639		emitopts(fp, cond->cx_u.and.right, include);
640		break;
641	default:
642		cfgerror("bug");
643	}
644}
645
646/*
647 * Emit appending makeoptions.
648 */
649static void
650emitappmkoptions(FILE *fp)
651{
652	struct nvlist *nv;
653	struct condexpr *cond;
654	size_t i;
655
656	for (i = 0; i < nselfiles; i++) {
657		struct files *const fi = selfiles[i];
658
659		if (fi->fi_optx) {
660			fprintf(fp, "OPT.%s.c+=", fi->fi_base);
661			emitopts(fp, fi->fi_optx, 1);
662			fprintf(fp, "\n");
663		}
664	}
665
666	for (nv = appmkoptions; nv != NULL; nv = nv->nv_next)
667		fprintf(fp, "%s+=%s\n", nv->nv_name, nv->nv_str);
668
669	for (nv = condmkoptions; nv != NULL; nv = nv->nv_next) {
670		cond = nv->nv_ptr;
671		if (expr_eval(cond, selectopt, NULL))
672			emitmkoption(fp, "+=", nv);
673		condexpr_destroy(cond);
674		nv->nv_ptr = NULL;
675	}
676}
677
678static int
679/*ARGSUSED*/
680selectopt(const char *name, void *context)
681{
682
683	return (ht_lookup(selecttab, strtolower(name)) != NULL);
684}
685