1 /*	$NetBSD: main.c,v 1.89 2015/09/04 06:01:40 uebayasi 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: @(#)main.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: main.c,v 1.89 2015/09/04 06:01:40 uebayasi Exp $");
49 
50 #ifndef MAKE_BOOTSTRAP
51 #include <sys/cdefs.h>
52 #define	COPYRIGHT(x)	__COPYRIGHT(x)
53 #else
54 #define	COPYRIGHT(x)	static const char copyright[] = x
55 #endif
56 
57 #ifndef lint
58 COPYRIGHT("@(#) Copyright (c) 1992, 1993\
59  The Regents of the University of California.  All rights reserved.");
60 #endif /* not lint */
61 
62 #include <sys/types.h>
63 #include <sys/stat.h>
64 #include <sys/param.h>
65 #include <sys/mman.h>
66 #if !HAVE_NBTOOL_CONFIG_H
67 #include <sys/sysctl.h>
68 #endif
69 #include <paths.h>
70 #include <ctype.h>
71 #include <err.h>
72 #include <errno.h>
73 #include <fcntl.h>
74 #include <limits.h>
75 #include <stdio.h>
76 #include <stdlib.h>
77 #include <string.h>
78 #include <unistd.h>
79 #include <vis.h>
80 #include <util.h>
81 
82 #include "defs.h"
83 #include "sem.h"
84 
85 #ifndef LINE_MAX
86 #define LINE_MAX 1024
87 #endif
88 
89 struct devbasetq allbases;
90 struct devatq alldevas;
91 struct conftq allcf;
92 struct devitq alldevi, allpseudo;
93 struct devmtq alldevms;
94 struct pspectq allpspecs;
95 
96 struct devi **packed;
97 size_t npacked;
98 
99 struct locators locators;
100 
101 int lkmmode;
102 const char *conffile;		/* source file, e.g., "GENERIC.sparc" */
103 const char *machine;		/* machine type, e.g., "sparc" or "sun3" */
104 const char *machinearch;	/* machine arch, e.g., "sparc" or "m68k" */
105 struct	nvlist *machinesubarches;
106 				/* machine subarches, e.g., "sun68k" or "hpc" */
107 const char *ioconfname;		/* ioconf name, mutually exclusive to machine */
108 const char *srcdir;		/* path to source directory (rel. to build) */
109 const char *builddir;		/* path to build directory */
110 const char *defbuilddir;	/* default build directory */
111 const char *ident;		/* kernel "ident"ification string */
112 int	errors;			/* counts calls to error() */
113 int	minmaxusers;		/* minimum "maxusers" parameter */
114 int	defmaxusers;		/* default "maxusers" parameter */
115 int	maxmaxusers;		/* default "maxusers" parameter */
116 int	maxusers;		/* configuration's "maxusers" parameter */
117 int	maxpartitions;		/* configuration's "maxpartitions" parameter */
118 int	version;		/* version of the configuration file */
119 struct	nvlist *options;	/* options */
120 struct	nvlist *fsoptions;	/* filesystems */
121 struct	nvlist *mkoptions;	/* makeoptions */
122 struct	nvlist *appmkoptions;	/* appending mkoptions */
123 struct	nvlist *condmkoptions;	/* conditional makeoption table */
124 struct	hashtab *devbasetab;	/* devbase lookup */
125 struct	hashtab *devroottab;	/* attach at root lookup */
126 struct	hashtab *devatab;	/* devbase attachment lookup */
127 struct	hashtab *deaddevitab;	/* removed instances lookup */
128 struct	hashtab *selecttab;	/* selects things that are "optional foo" */
129 struct	hashtab *needcnttab;	/* retains names marked "needs-count" */
130 struct	hashtab *opttab;	/* table of configured options */
131 struct	hashtab *fsopttab;	/* table of configured file systems */
132 struct	dlhash *defopttab;	/* options that have been "defopt"'d */
133 struct	dlhash *defflagtab;	/* options that have been "defflag"'d */
134 struct	dlhash *defparamtab;	/* options that have been "defparam"'d */
135 struct	dlhash *defoptlint;	/* lint values for options */
136 struct	nvhash *deffstab;	/* defined file systems */
137 struct	dlhash *optfiletab;	/* "defopt"'d option .h files */
138 struct	hashtab *attrtab;	/* attributes (locators, etc.) */
139 struct	hashtab *attrdeptab;	/* attribute dependencies */
140 struct	hashtab *bdevmtab;	/* block devm lookup */
141 struct	hashtab *cdevmtab;	/* character devm lookup */
142 
143 int	ndevi;				/* number of devi's (before packing) */
144 int	npspecs;			/* number of parent specs */
145 devmajor_t maxbdevm;			/* max number of block major */
146 devmajor_t maxcdevm;			/* max number of character major */
147 int	do_devsw;			/* 0 if pre-devsw config */
148 int	oktopackage;			/* 0 before setmachine() */
149 int	devilevel;			/* used for devi->i_level */
150 
151 struct filelist		allfiles;	/* list of all kernel source files */
152 struct filelist		allcfiles;	/* list of all .c files */
153 struct filelist		allsfiles;	/* list of all .S files */
154 struct filelist		allofiles;	/* list of all .o files */
155 
156 struct prefixlist	prefixes,	/* prefix stack */
157 			allprefixes;	/* all prefixes used (after popped) */
158 struct prefixlist	buildprefixes,	/* build prefix stack */
159 			allbuildprefixes;/* all build prefixes used (after popped) */
160 
161 int	vflag;				/* verbose output */
162 int	Pflag;				/* pack locators */
163 int	Lflag;				/* lint config generation */
164 int	Mflag;				/* modular build */
165 int	Sflag;				/* suffix rules & subdirectory */
166 int	handling_cmdlineopts;		/* currently processing -D/-U options */
167 
168 int	yyparse(void);
169 
170 #ifndef MAKE_BOOTSTRAP
171 extern int yydebug;
172 #endif
173 int	dflag;
174 
175 static struct dlhash *obsopttab;
176 static struct hashtab *mkopttab;
177 static struct nvlist **nextopt;
178 static struct nvlist **nextmkopt;
179 static struct nvlist **nextappmkopt;
180 static struct nvlist **nextcndmkopt;
181 static struct nvlist **nextfsopt;
182 static struct nvlist *cmdlinedefs, *cmdlineundefs;
183 
184 static	void	usage(void) __dead;
185 static	void	dependopts(void);
186 static	void	dependopts_one(const char *);
187 static	void	do_depends(struct nvlist *);
188 static	void	do_depend(struct nvlist *);
189 static	void	stop(void);
190 static	int	do_option(struct hashtab *, struct nvlist **,
191 		    struct nvlist ***, const char *, const char *,
192 		    const char *, struct hashtab *);
193 static	int	undo_option(struct hashtab *, struct nvlist **,
194 		    struct nvlist ***, const char *, const char *);
195 static	int	crosscheck(void);
196 static	int	badstar(void);
197 	int	main(int, char **);
198 static	int	mkallsubdirs(void);
199 static	int	mksymlinks(void);
200 static	int	mkident(void);
201 static	int	devbase_has_dead_instances(const char *, void *, void *);
202 static	int	devbase_has_any_instance(struct devbase *, int, int, int);
203 static	int	check_dead_devi(const char *, void *, void *);
204 static	void	add_makeopt(const char *);
205 static	void	remove_makeopt(const char *);
206 static	void	handle_cmdline_makeoptions(void);
207 static	void	kill_orphans(void);
208 static	void	do_kill_orphans(struct devbase *, struct attr *,
209     struct devbase *, int);
210 static	int	kill_orphans_cb(const char *, void *, void *);
211 static	int	cfcrosscheck(struct config *, const char *, struct nvlist *);
212 static void	defopt(struct dlhash *ht, const char *fname,
213 	     struct defoptlist *opts, struct nvlist *deps, int obs);
214 static struct defoptlist *find_declared_option_option(const char *name);
215 static struct nvlist *find_declared_fs_option(const char *name);
216 
217 #define LOGCONFIG_LARGE "INCLUDE_CONFIG_FILE"
218 #define LOGCONFIG_SMALL "INCLUDE_JUST_CONFIG"
219 
220 static	void	logconfig_start(void);
221 static	void	logconfig_end(void);
222 static	FILE	*cfg;
223 static	time_t	cfgtime;
224 
225 static	int	is_elf(const char *);
226 static	int	extract_config(const char *, const char *, int);
227 
228 int badfilename(const char *fname);
229 
230 const char *progname;
231 extern const char *yyfile;
232 
233 int
main(int argc,char ** argv)234 main(int argc, char **argv)
235 {
236 	char *p, cname[PATH_MAX];
237 	const char *last_component;
238 	int pflag, xflag, ch, removeit;
239 
240 	setprogname(argv[0]);
241 
242 	pflag = 0;
243 	xflag = 0;
244 	while ((ch = getopt(argc, argv, "D:LMPSU:dgpvb:s:x")) != -1) {
245 		switch (ch) {
246 
247 		case 'd':
248 #ifndef MAKE_BOOTSTRAP
249 			yydebug = 1;
250 #endif
251 			dflag++;
252 			break;
253 
254 		case 'M':
255 			Mflag = 1;
256 			break;
257 
258 		case 'L':
259 			Lflag = 1;
260 			break;
261 
262 		case 'P':
263 			Pflag = 1;
264 			break;
265 
266 		case 'g':
267 			/*
268 			 * In addition to DEBUG, you probably wanted to
269 			 * set "options KGDB" and maybe others.  We could
270 			 * do that for you, but you really should just
271 			 * put them in the config file.
272 			 */
273 			warnx("-g is obsolete (use -D DEBUG=\"-g\")");
274 			usage();
275 			/*NOTREACHED*/
276 
277 		case 'p':
278 			/*
279 			 * Essentially the same as makeoptions PROF="-pg",
280 			 * but also changes the path from ../../compile/FOO
281 			 * to ../../compile/FOO.PROF; i.e., compile a
282 			 * profiling kernel based on a typical "regular"
283 			 * kernel.
284 			 *
285 			 * Note that if you always want profiling, you
286 			 * can (and should) use a "makeoptions" line.
287 			 */
288 			pflag = 1;
289 			break;
290 
291 		case 'v':
292 			vflag = 1;
293 			break;
294 
295 		case 'b':
296 			builddir = optarg;
297 			break;
298 
299 		case 's':
300 			srcdir = optarg;
301 			break;
302 
303 		case 'S':
304 			Sflag = 1;
305 			break;
306 
307 		case 'x':
308 			xflag = 1;
309 			break;
310 
311 		case 'D':
312 			add_makeopt(optarg);
313 			break;
314 
315 		case 'U':
316 			remove_makeopt(optarg);
317 			break;
318 
319 		case '?':
320 		default:
321 			usage();
322 		}
323 	}
324 
325 	if (xflag && optind != 2) {
326 		errx(EXIT_FAILURE, "-x must be used alone");
327 	}
328 
329 	argc -= optind;
330 	argv += optind;
331 	if (argc > 1) {
332 		usage();
333 	}
334 
335 	if (Lflag && (builddir != NULL || Pflag || pflag))
336 		errx(EXIT_FAILURE, "-L can only be used with -s and -v");
337 
338 	if (xflag) {
339 		if (argc == 0) {
340 #if !HAVE_NBTOOL_CONFIG_H
341 			char path_unix[MAXPATHLEN];
342 			size_t len = sizeof(path_unix) - 1;
343 			path_unix[0] = '/';
344 
345 			conffile = sysctlbyname("machdep.booted_kernel",
346 			    &path_unix[1], &len, NULL, 0) == -1 ? _PATH_UNIX :
347 			    path_unix;
348 #else
349 			errx(EXIT_FAILURE, "no kernel supplied");
350 #endif
351 		} else
352 			conffile = argv[0];
353 		if (!is_elf(conffile))
354 			errx(EXIT_FAILURE, "%s: not a binary kernel",
355 			    conffile);
356 		if (!extract_config(conffile, "stdout", STDOUT_FILENO))
357 			errx(EXIT_FAILURE, "%s does not contain embedded "
358 			    "configuration data", conffile);
359 		exit(0);
360 	}
361 
362 	conffile = (argc == 1) ? argv[0] : "CONFIG";
363 	if (firstfile(conffile)) {
364 		err(EXIT_FAILURE, "Cannot read `%s'", conffile);
365 		exit(2);
366 	}
367 
368 	/*
369 	 * Init variables.
370 	 */
371 	minmaxusers = 1;
372 	maxmaxusers = 10000;
373 	initintern();
374 	ident = NULL;
375 	devbasetab = ht_new();
376 	devroottab = ht_new();
377 	devatab = ht_new();
378 	devitab = ht_new();
379 	deaddevitab = ht_new();
380 	selecttab = ht_new();
381 	needcnttab = ht_new();
382 	opttab = ht_new();
383 	mkopttab = ht_new();
384 	fsopttab = ht_new();
385 	deffstab = nvhash_create();
386 	defopttab = dlhash_create();
387 	defparamtab = dlhash_create();
388 	defoptlint = dlhash_create();
389 	defflagtab = dlhash_create();
390 	optfiletab = dlhash_create();
391 	obsopttab = dlhash_create();
392 	bdevmtab = ht_new();
393 	maxbdevm = 0;
394 	cdevmtab = ht_new();
395 	maxcdevm = 0;
396 	nextopt = &options;
397 	nextmkopt = &mkoptions;
398 	nextappmkopt = &appmkoptions;
399 	nextcndmkopt = &condmkoptions;
400 	nextfsopt = &fsoptions;
401 	initfiles();
402 	initsem();
403 
404 	/*
405 	 * Handle profiling (must do this before we try to create any
406 	 * files).
407 	 */
408 	last_component = strrchr(conffile, '/');
409 	last_component = (last_component) ? last_component + 1 : conffile;
410 	if (pflag) {
411 		p = emalloc(strlen(last_component) + 17);
412 		(void)sprintf(p, "../compile/%s.PROF", last_component);
413 		(void)addmkoption(intern("PROF"), "-pg");
414 		(void)addoption(intern("GPROF"), NULL);
415 	} else {
416 		p = emalloc(strlen(last_component) + 13);
417 		(void)sprintf(p, "../compile/%s", last_component);
418 	}
419 	defbuilddir = (argc == 0) ? "." : p;
420 
421 	if (Lflag) {
422 		char resolvedname[MAXPATHLEN];
423 
424 		if (realpath(conffile, resolvedname) == NULL)
425 			err(EXIT_FAILURE, "realpath(%s)", conffile);
426 
427 		if (yyparse())
428 			stop();
429 
430 		printf("include \"%s\"\n", resolvedname);
431 
432 		emit_params();
433 		emit_options();
434 		emit_instances();
435 
436 		exit(EXIT_SUCCESS);
437 	}
438 
439 	removeit = 0;
440 	if (is_elf(conffile)) {
441 		const char *tmpdir;
442 		int cfd;
443 
444 		if (builddir == NULL)
445 			errx(EXIT_FAILURE, "Build directory must be specified "
446 			    "with binary kernels");
447 
448 		/* Open temporary configuration file */
449 		tmpdir = getenv("TMPDIR");
450 		if (tmpdir == NULL)
451 			tmpdir = _PATH_TMP;
452 		snprintf(cname, sizeof(cname), "%s/config.tmp.XXXXXX", tmpdir);
453 		cfd = mkstemp(cname);
454 		if (cfd == -1)
455 			err(EXIT_FAILURE, "Cannot create `%s'", cname);
456 
457 		printf("Using configuration data embedded in kernel...\n");
458 		if (!extract_config(conffile, cname, cfd)) {
459 			unlink(cname);
460 			errx(EXIT_FAILURE, "%s does not contain embedded "
461 			    "configuration data", conffile);
462 		}
463 
464 		removeit = 1;
465 		close(cfd);
466 		firstfile(cname);
467 	}
468 
469 	 /*
470 	  * Log config file.  We don't know until yyparse() if we're
471 	  * going to need config_file.h (i.e. if we're doing ioconf-only
472 	  * or not).  Just start creating the file, and when we know
473 	  * later, we'll just keep or discard our work here.
474 	  */
475 	logconfig_start();
476 
477 	/*
478 	 * Parse config file (including machine definitions).
479 	 */
480 	if (yyparse())
481 		stop();
482 
483 	if (ioconfname && cfg)
484 		fclose(cfg);
485 	else
486 		logconfig_end();
487 
488 	if (removeit)
489 		unlink(cname);
490 
491 	/*
492 	 * Handle command line overrides
493 	 */
494 	yyfile = "handle_cmdline_makeoptions";
495 	handle_cmdline_makeoptions();
496 
497 	/*
498 	 * Detect and properly ignore orphaned devices
499 	 */
500 	yyfile = "kill_orphans";
501 	kill_orphans();
502 
503 	/*
504 	 * Select devices and pseudo devices and their attributes
505 	 */
506 	yyfile = "fixdevis";
507 	if (fixdevis())
508 		stop();
509 
510 	/*
511 	 * Copy maxusers to param.
512 	 */
513 	yyfile = "fixmaxusers";
514 	fixmaxusers();
515 
516 	/*
517 	 * Copy makeoptions to params
518 	 */
519 	yyfile = "fixmkoption";
520 	fixmkoption();
521 
522 	/*
523 	 * If working on an ioconf-only config, process here and exit
524 	 */
525 	if (ioconfname) {
526 		yyfile = "pack";
527 		pack();
528 		yyfile = "mkioconf";
529 		mkioconf();
530 		yyfile = "emitlocs";
531 		emitlocs();
532 		yyfile = "emitioconfh";
533 		emitioconfh();
534 		return 0;
535 	}
536 
537 	yyfile = "dependattrs";
538 	dependattrs();
539 
540 	/*
541 	 * Deal with option dependencies.
542 	 */
543 	yyfile = "dependopts";
544 	dependopts();
545 
546 	/*
547 	 * Fix (as in `set firmly in place') files.
548 	 */
549 	yyfile = "fixfiles";
550 	if (fixfiles())
551 		stop();
552 
553 	/*
554 	 * Fix device-majors.
555 	 */
556 	yyfile = "fixdevsw";
557 	if (fixdevsw())
558 		stop();
559 
560 	/*
561 	 * Perform cross-checking.
562 	 */
563 	if (maxusers == 0) {
564 		if (defmaxusers) {
565 			(void)printf("maxusers not specified; %d assumed\n",
566 			    defmaxusers);
567 			maxusers = defmaxusers;
568 		} else {
569 			warnx("need \"maxusers\" line");
570 			errors++;
571 		}
572 	}
573 	if (crosscheck() || errors)
574 		stop();
575 
576 	/*
577 	 * Squeeze things down and finish cross-checks (STAR checks must
578 	 * run after packing).
579 	 */
580 	yyfile = "pack";
581 	pack();
582 	yyfile = "badstar";
583 	if (badstar())
584 		stop();
585 
586 	yyfile = NULL;
587 	/*
588 	 * Ready to go.  Build all the various files.
589 	 */
590 	if ((Sflag && mkallsubdirs()) || mksymlinks() || mkmakefile() || mkheaders() || mkswap() ||
591 	    mkioconf() || (do_devsw ? mkdevsw() : 0) || mkident() || errors)
592 		stop();
593 	(void)printf("Build directory is %s\n", builddir);
594 	(void)printf("Don't forget to run \"make depend\"\n");
595 
596 	return 0;
597 }
598 
599 static void
usage(void)600 usage(void)
601 {
602 	(void)fprintf(stderr, "Usage: %s [-Ppv] [-b builddir] [-D var=value] "
603 	    "[-s srcdir] [-U var] "
604 	    "[config-file]\n\t%s -x [kernel-file]\n"
605 	    "\t%s -L [-v] [-s srcdir] [config-file]\n",
606 	    getprogname(), getprogname(), getprogname());
607 	exit(1);
608 }
609 
610 /*
611  * Set any options that are implied by other options.
612  */
613 static void
dependopts(void)614 dependopts(void)
615 {
616 	struct nvlist *nv;
617 
618 	for (nv = options; nv != NULL; nv = nv->nv_next) {
619 		dependopts_one(nv->nv_name);
620 	}
621 
622 	for (nv = fsoptions; nv != NULL; nv = nv->nv_next) {
623 		dependopts_one(nv->nv_name);
624 	}
625 }
626 
627 static void
dependopts_one(const char * name)628 dependopts_one(const char *name)
629 {
630 	struct defoptlist *dl;
631 	struct nvlist *fs;
632 
633 	dl = find_declared_option_option(name);
634 	if (dl != NULL) {
635 		do_depends(dl->dl_depends);
636 	}
637 	fs = find_declared_fs_option(name);
638 	if (fs != NULL) {
639 		do_depends(fs->nv_ptr);
640 	}
641 
642 	CFGDBG(3, "depend `%s' searched", name);
643 }
644 
645 static void
do_depends(struct nvlist * nv)646 do_depends(struct nvlist *nv)
647 {
648 	struct nvlist *opt;
649 
650 	for (opt = nv; opt != NULL; opt = opt->nv_next) {
651 		do_depend(opt);
652 	}
653 }
654 
655 static void
do_depend(struct nvlist * nv)656 do_depend(struct nvlist *nv)
657 {
658 	struct attr *a;
659 
660 	if (nv != NULL && (nv->nv_flags & NV_DEPENDED) == 0) {
661 		nv->nv_flags |= NV_DEPENDED;
662 		/*
663 		 * If the dependency is an attribute, then just add
664 		 * it to the selecttab.
665 		 */
666 		CFGDBG(3, "depend attr `%s'", nv->nv_name);
667 		if ((a = ht_lookup(attrtab, nv->nv_name)) != NULL) {
668 			if (a->a_iattr)
669 				panic("do_depend(%s): dep `%s' is an iattr",
670 				    nv->nv_name, a->a_name);
671 			expandattr(a, selectattr);
672 		} else {
673 			if (ht_lookup(opttab, nv->nv_name) == NULL)
674 				addoption(nv->nv_name, NULL);
675 			dependopts_one(nv->nv_name);
676 		}
677 	}
678 }
679 
680 static int
recreate(const char * p,const char * q)681 recreate(const char *p, const char *q)
682 {
683 	int ret;
684 
685 	if ((ret = unlink(q)) == -1 && errno != ENOENT)
686 		warn("unlink(%s)", q);
687 	if ((ret = symlink(p, q)) == -1)
688 		warn("symlink(%s -> %s)", q, p);
689 	return ret;
690 }
691 
692 static void
mksubdir(char * buf)693 mksubdir(char *buf)
694 {
695 	char *p;
696 	struct stat st;
697 
698 	p = strrchr(buf, '/');
699 	if (p != NULL && *p == '/') {
700 		*p = '\0';
701 		mksubdir(buf);
702 		*p = '/';
703 	}
704 	if (stat(buf, &st) == 0) {
705 		if (!S_ISDIR(st.st_mode))
706 			errx(EXIT_FAILURE, "not directory %s", buf);
707 	} else
708 		if (mkdir(buf, 0777) == -1)
709 			errx(EXIT_FAILURE, "cannot create %s", buf);
710 }
711 
712 static int
mksubdirs(struct filelist * fl)713 mksubdirs(struct filelist *fl)
714 {
715 	struct files *fi;
716 	const char *prologue, *prefix, *sep;
717 	char buf[MAXPATHLEN];
718 
719 	TAILQ_FOREACH(fi, fl, fi_next) {
720 		if ((fi->fi_flags & FI_SEL) == 0)
721 			continue;
722 		prefix = sep = "";
723 		if (fi->fi_buildprefix != NULL) {
724 			prefix = fi->fi_buildprefix;
725 			sep = "/";
726 		} else {
727 			if (fi->fi_prefix != NULL) {
728 				prefix = fi->fi_prefix;
729 				sep = "/";
730 			}
731 		}
732 		snprintf(buf, sizeof(buf), "%s%s%s", prefix, sep, fi->fi_dir);
733 		if (buf[0] == '\0')
734 			continue;
735 		mksubdir(buf);
736 		if (fi->fi_prefix != NULL && fi->fi_buildprefix != NULL) {
737 			char org[MAXPATHLEN];
738 
739 			if (fi->fi_prefix[0] == '/') {
740 				prologue = "";
741 				sep = "";
742 			} else {
743 				prologue = srcdir;
744 				sep = "/";
745 			}
746 			snprintf(buf, sizeof(buf), "%s%s%s",
747 			    fi->fi_buildprefix, "/", fi->fi_path);
748 			snprintf(org, sizeof(org), "%s%s%s%s%s",
749 			    prologue, sep, fi->fi_prefix, "/", fi->fi_path);
750 			recreate(org, buf);
751 			fi->fi_prefix = fi->fi_buildprefix;
752 			fi->fi_buildprefix = NULL;
753 		}
754 	}
755 
756 	return 0;
757 }
758 
759 static int
mkallsubdirs(void)760 mkallsubdirs(void)
761 {
762 
763 	mksubdirs(&allfiles);
764 	mksubdirs(&allofiles);
765 	return 0;
766 }
767 
768 /*
769  * Make a symlink for "machine" so that "#include <machine/foo.h>" works,
770  * and for the machine's CPU architecture, so that works as well.
771  */
772 static int
mksymlinks(void)773 mksymlinks(void)
774 {
775 	int ret;
776 	char *p, buf[MAXPATHLEN];
777 	const char *q;
778 	struct nvlist *nv;
779 
780 	p = buf;
781 
782 	snprintf(buf, sizeof(buf), "%s/arch/%s/include", srcdir, machine);
783 	ret = recreate(p, "machine");
784 	ret = recreate(p, machine);
785 
786 	if (machinearch != NULL) {
787 		snprintf(buf, sizeof(buf), "%s/arch/%s/include", srcdir, machinearch);
788 		q = machinearch;
789 	} else {
790 		snprintf(buf, sizeof(buf), "machine");
791 		q = machine;
792 	}
793 
794 	ret = recreate(p, q);
795 
796 	for (nv = machinesubarches; nv != NULL; nv = nv->nv_next) {
797 		q = nv->nv_name;
798 		snprintf(buf, sizeof(buf), "%s/arch/%s/include", srcdir, q);
799 		ret = recreate(p, q);
800 	}
801 
802 	return (ret);
803 }
804 
805 static __dead void
stop(void)806 stop(void)
807 {
808 	(void)fprintf(stderr, "*** Stop.\n");
809 	exit(1);
810 }
811 
812 static void
check_dependencies(const char * thing,struct nvlist * deps)813 check_dependencies(const char *thing, struct nvlist *deps)
814 {
815 	struct nvlist *dep;
816 	struct attr *a;
817 
818 	for (dep = deps; dep != NULL; dep = dep->nv_next) {
819 		/*
820 		 * If the dependency is an attribute, it must not
821 		 * be an interface attribute.  Otherwise, it must
822 		 * be a previously declared option.
823 		 */
824 		if ((a = ht_lookup(attrtab, dep->nv_name)) != NULL) {
825 			if (a->a_iattr)
826 				cfgerror("option `%s' dependency `%s' "
827 				    "is an interface attribute",
828 				    thing, a->a_name);
829 		} else if (OPT_OBSOLETE(dep->nv_name)) {
830 			cfgerror("option `%s' dependency `%s' "
831 			    "is obsolete", thing, dep->nv_name);
832 		} else if (!is_declared_option(dep->nv_name)) {
833 			cfgerror("option `%s' dependency `%s' "
834 			    "is an unknown option",
835 			    thing, dep->nv_name);
836 		}
837 	}
838 }
839 
840 static void
add_fs_dependencies(struct nvlist * nv,struct nvlist * deps)841 add_fs_dependencies(struct nvlist *nv, struct nvlist *deps)
842 {
843 	/* Use nv_ptr to link any other options that are implied. */
844 	nv->nv_ptr = deps;
845 	check_dependencies(nv->nv_name, deps);
846 }
847 
848 static void
add_opt_dependencies(struct defoptlist * dl,struct nvlist * deps)849 add_opt_dependencies(struct defoptlist *dl, struct nvlist *deps)
850 {
851 	dl->dl_depends = deps;
852 	check_dependencies(dl->dl_name, deps);
853 }
854 
855 /*
856  * Define one or more file systems.
857  */
858 void
deffilesystem(struct nvlist * fses,struct nvlist * deps)859 deffilesystem(struct nvlist *fses, struct nvlist *deps)
860 {
861 	struct nvlist *nv;
862 
863 	/*
864 	 * Mark these options as ones to skip when creating the Makefile.
865 	 */
866 	for (nv = fses; nv != NULL; nv = nv->nv_next) {
867 		if (DEFINED_OPTION(nv->nv_name)) {
868 			cfgerror("file system or option `%s' already defined",
869 			    nv->nv_name);
870 			return;
871 		}
872 
873 		/*
874 		 * Also mark it as a valid file system, which may be
875 		 * used in "file-system" directives in the config
876 		 * file.
877 		 */
878 		if (nvhash_insert(deffstab, nv->nv_name, nv))
879 			panic("file system `%s' already in table?!",
880 			    nv->nv_name);
881 
882 		add_fs_dependencies(nv, deps);
883 
884 		/*
885 		 * Implicit attribute definition for filesystem.
886 		 */
887 		const char *n;
888 		n = strtolower(nv->nv_name);
889 		refattr(n);
890 	}
891 }
892 
893 /*
894  * Sanity check a file name.
895  */
896 int
badfilename(const char * fname)897 badfilename(const char *fname)
898 {
899 	const char *n;
900 
901 	/*
902 	 * We're putting multiple options into one file.  Sanity
903 	 * check the file name.
904 	 */
905 	if (strchr(fname, '/') != NULL) {
906 		cfgerror("option file name contains a `/'");
907 		return 1;
908 	}
909 	if ((n = strrchr(fname, '.')) == NULL || strcmp(n, ".h") != 0) {
910 		cfgerror("option file name does not end in `.h'");
911 		return 1;
912 	}
913 	return 0;
914 }
915 
916 
917 /*
918  * Search for a defined option (defopt, filesystem, etc), and if found,
919  * return the option's struct nvlist.
920  *
921  * This used to be one function (find_declared_option) before options
922  * and filesystems became different types.
923  */
924 static struct defoptlist *
find_declared_option_option(const char * name)925 find_declared_option_option(const char *name)
926 {
927 	struct defoptlist *option;
928 
929 	if ((option = dlhash_lookup(defopttab, name)) != NULL ||
930 	    (option = dlhash_lookup(defparamtab, name)) != NULL ||
931 	    (option = dlhash_lookup(defflagtab, name)) != NULL) {
932 		return (option);
933 	}
934 
935 	return (NULL);
936 }
937 
938 static struct nvlist *
find_declared_fs_option(const char * name)939 find_declared_fs_option(const char *name)
940 {
941 	struct nvlist *fs;
942 
943 	if ((fs = nvhash_lookup(deffstab, name)) != NULL) {
944 		return fs;
945 	}
946 
947 	return (NULL);
948 }
949 
950 /*
951  * Like find_declared_option but doesn't return what it finds, so it
952  * can search both the various kinds of options and also filesystems.
953  */
954 int
is_declared_option(const char * name)955 is_declared_option(const char *name)
956 {
957 	struct defoptlist *option = NULL;
958 	struct nvlist *fs;
959 
960 	if ((option = dlhash_lookup(defopttab, name)) != NULL ||
961 	    (option = dlhash_lookup(defparamtab, name)) != NULL ||
962 	    (option = dlhash_lookup(defflagtab, name)) != NULL) {
963 		return 1;
964 	}
965 	if ((fs = nvhash_lookup(deffstab, name)) != NULL) {
966 		return 1;
967 	}
968 
969 	return 0;
970 }
971 
972 /*
973  * Define one or more standard options.  If an option file name is specified,
974  * place all options in one file with the specified name.  Otherwise, create
975  * an option file for each option.
976  * record the option information in the specified table.
977  */
978 void
defopt(struct dlhash * ht,const char * fname,struct defoptlist * opts,struct nvlist * deps,int obs)979 defopt(struct dlhash *ht, const char *fname, struct defoptlist *opts,
980        struct nvlist *deps, int obs)
981 {
982 	struct defoptlist *dl, *nextdl, *olddl;
983 	const char *name;
984 	char buf[500];
985 
986 	if (fname != NULL && badfilename(fname)) {
987 		return;
988 	}
989 
990 	/*
991 	 * Mark these options as ones to skip when creating the Makefile.
992 	 */
993 	for (dl = opts; dl != NULL; dl = nextdl) {
994 		nextdl = dl->dl_next;
995 
996 		if (dl->dl_lintvalue != NULL) {
997 			/*
998 			 * If an entry already exists, then we are about to
999 			 * complain, so no worry.
1000 			 */
1001 			(void) dlhash_insert(defoptlint, dl->dl_name,
1002 			    dl);
1003 		}
1004 
1005 		/* An option name can be declared at most once. */
1006 		if (DEFINED_OPTION(dl->dl_name)) {
1007 			cfgerror("file system or option `%s' already defined",
1008 			    dl->dl_name);
1009 			return;
1010 		}
1011 
1012 		if (dlhash_insert(ht, dl->dl_name, dl)) {
1013 			cfgerror("file system or option `%s' already defined",
1014 			    dl->dl_name);
1015 			return;
1016 		}
1017 
1018 		if (fname == NULL) {
1019 			/*
1020 			 * Each option will be going into its own file.
1021 			 * Convert the option name to lower case.  This
1022 			 * lower case name will be used as the option
1023 			 * file name.
1024 			 */
1025 			(void) snprintf(buf, sizeof(buf), "opt_%s.h",
1026 			    strtolower(dl->dl_name));
1027 			name = intern(buf);
1028 		} else {
1029 			name = fname;
1030 		}
1031 
1032 		add_opt_dependencies(dl, deps);
1033 
1034 		/*
1035 		 * Remove this option from the parameter list before adding
1036 		 * it to the list associated with this option file.
1037 		 */
1038 		dl->dl_next = NULL;
1039 
1040 		/*
1041 		 * Flag as obsolete, if requested.
1042 		 */
1043 		if (obs) {
1044 			dl->dl_obsolete = 1;
1045 			(void)dlhash_insert(obsopttab, dl->dl_name, dl);
1046 		}
1047 
1048 		/*
1049 		 * Add this option file if we haven't seen it yet.
1050 		 * Otherwise, append to the list of options already
1051 		 * associated with this file.
1052 		 */
1053 		if ((olddl = dlhash_lookup(optfiletab, name)) == NULL) {
1054 			(void)dlhash_insert(optfiletab, name, dl);
1055 		} else {
1056 			while (olddl->dl_next != NULL)
1057 				olddl = olddl->dl_next;
1058 			olddl->dl_next = dl;
1059 		}
1060 	}
1061 }
1062 
1063 /*
1064  * Define one or more standard options.  If an option file name is specified,
1065  * place all options in one file with the specified name.  Otherwise, create
1066  * an option file for each option.
1067  */
1068 void
defoption(const char * fname,struct defoptlist * opts,struct nvlist * deps)1069 defoption(const char *fname, struct defoptlist *opts, struct nvlist *deps)
1070 {
1071 
1072 	cfgwarn("The use of `defopt' is deprecated");
1073 	defopt(defopttab, fname, opts, deps, 0);
1074 }
1075 
1076 
1077 /*
1078  * Define an option for which a value is required.
1079  */
1080 void
defparam(const char * fname,struct defoptlist * opts,struct nvlist * deps,int obs)1081 defparam(const char *fname, struct defoptlist *opts, struct nvlist *deps, int obs)
1082 {
1083 
1084 	defopt(defparamtab, fname, opts, deps, obs);
1085 }
1086 
1087 /*
1088  * Define an option which must not have a value, and which
1089  * emits a "needs-flag" style output.
1090  */
1091 void
defflag(const char * fname,struct defoptlist * opts,struct nvlist * deps,int obs)1092 defflag(const char *fname, struct defoptlist *opts, struct nvlist *deps, int obs)
1093 {
1094 
1095 	defopt(defflagtab, fname, opts, deps, obs);
1096 }
1097 
1098 
1099 /*
1100  * Add an option from "options FOO".  Note that this selects things that
1101  * are "optional foo".
1102  */
1103 void
addoption(const char * name,const char * value)1104 addoption(const char *name, const char *value)
1105 {
1106 	const char *n;
1107 	int is_fs, is_param, is_flag, is_undecl, is_obs;
1108 
1109 	/*
1110 	 * Figure out how this option was declared (if at all.)
1111 	 * XXX should use "params" and "flags" in config.
1112 	 * XXX crying out for a type field in a unified hashtab.
1113 	 */
1114 	is_fs = OPT_FSOPT(name);
1115 	is_param = OPT_DEFPARAM(name);
1116 	is_flag =  OPT_DEFFLAG(name);
1117 	is_obs = OPT_OBSOLETE(name);
1118 	is_undecl = !DEFINED_OPTION(name);
1119 
1120 	/* Warn and pretend the user had not selected the option  */
1121 	if (is_obs) {
1122 		cfgwarn("obsolete option `%s' will be ignored", name);
1123 		return;
1124 	}
1125 
1126 	/* Make sure this is not a defined file system. */
1127 	if (is_fs) {
1128 		cfgerror("`%s' is a defined file system", name);
1129 		return;
1130 	}
1131 	/* A defparam must have a value */
1132 	if (is_param && value == NULL) {
1133 		cfgerror("option `%s' must have a value", name);
1134 		return;
1135 	}
1136 	/* A defflag must not have a value */
1137 	if (is_flag && value != NULL) {
1138 		cfgerror("option `%s' must not have a value", name);
1139 		return;
1140 	}
1141 
1142 	if (is_undecl && vflag) {
1143 		cfgwarn("undeclared option `%s' added to IDENT", name);
1144 	}
1145 
1146 	if (do_option(opttab, &options, &nextopt, name, value, "options",
1147 	    selecttab))
1148 		return;
1149 
1150 	/* make lowercase, then add to select table */
1151 	n = strtolower(name);
1152 	(void)ht_insert(selecttab, n, (void *)__UNCONST(n));
1153 	CFGDBG(3, "option selected `%s'", n);
1154 }
1155 
1156 void
deloption(const char * name)1157 deloption(const char *name)
1158 {
1159 
1160 	CFGDBG(4, "deselecting opt `%s'", name);
1161 	if (undo_option(opttab, &options, &nextopt, name, "options"))
1162 		return;
1163 	if (undo_option(selecttab, NULL, NULL, strtolower(name), "options"))
1164 		return;
1165 }
1166 
1167 /*
1168  * Add a file system option.  This routine simply inserts the name into
1169  * a list of valid file systems, which is used to validate the root
1170  * file system type.  The name is then treated like a standard option.
1171  */
1172 void
addfsoption(const char * name)1173 addfsoption(const char *name)
1174 {
1175 	const char *n;
1176 
1177 	/* Make sure this is a defined file system. */
1178 	if (!OPT_FSOPT(name)) {
1179 		cfgerror("`%s' is not a defined file system", name);
1180 		return;
1181 	}
1182 
1183 	/*
1184 	 * Convert to lower case.  This will be used in the select
1185 	 * table, to verify root file systems.
1186 	 */
1187 	n = strtolower(name);
1188 
1189 	if (do_option(fsopttab, &fsoptions, &nextfsopt, name, n, "file-system",
1190 	    selecttab))
1191 		return;
1192 
1193 	/* Add to select table. */
1194 	(void)ht_insert(selecttab, n, __UNCONST(n));
1195 	CFGDBG(3, "fs selected `%s'", name);
1196 
1197 	/*
1198 	 * Select attribute if one exists.
1199 	 */
1200 	struct attr *a;
1201 	if ((a = ht_lookup(attrtab, n)) != NULL)
1202 		selectattr(a);
1203 }
1204 
1205 void
delfsoption(const char * name)1206 delfsoption(const char *name)
1207 {
1208 	const char *n;
1209 
1210 	CFGDBG(4, "deselecting fs `%s'", name);
1211 	n = strtolower(name);
1212 	if (undo_option(fsopttab, &fsoptions, &nextfsopt, name, "file-system"))
1213 		return;
1214 	if (undo_option(selecttab, NULL, NULL, n, "file-system"))
1215 		return;
1216 }
1217 
1218 /*
1219  * Add a "make" option.
1220  */
1221 void
addmkoption(const char * name,const char * value)1222 addmkoption(const char *name, const char *value)
1223 {
1224 
1225 	(void)do_option(mkopttab, &mkoptions, &nextmkopt, name, value,
1226 		        "makeoptions", NULL);
1227 }
1228 
1229 void
delmkoption(const char * name)1230 delmkoption(const char *name)
1231 {
1232 
1233 	CFGDBG(4, "deselecting mkopt `%s'", name);
1234 	(void)undo_option(mkopttab, &mkoptions, &nextmkopt, name,
1235 	    "makeoptions");
1236 }
1237 
1238 /*
1239  * Add an appending "make" option.
1240  */
1241 void
appendmkoption(const char * name,const char * value)1242 appendmkoption(const char *name, const char *value)
1243 {
1244 	struct nvlist *nv;
1245 
1246 	nv = newnv(name, value, NULL, 0, NULL);
1247 	*nextappmkopt = nv;
1248 	nextappmkopt = &nv->nv_next;
1249 }
1250 
1251 /*
1252  * Add a conditional appending "make" option.
1253  */
1254 void
appendcondmkoption(struct condexpr * cond,const char * name,const char * value)1255 appendcondmkoption(struct condexpr *cond, const char *name, const char *value)
1256 {
1257 	struct nvlist *nv;
1258 
1259 	nv = newnv(name, value, cond, 0, NULL);
1260 	*nextcndmkopt = nv;
1261 	nextcndmkopt = &nv->nv_next;
1262 }
1263 
1264 /*
1265  * Copy maxusers to param "MAXUSERS".
1266  */
1267 void
fixmaxusers(void)1268 fixmaxusers(void)
1269 {
1270 	char str[32];
1271 
1272 	snprintf(str, sizeof(str), "%d", maxusers);
1273 	addoption(intern("MAXUSERS"), intern(str));
1274 }
1275 
1276 /*
1277  * Copy makeoptions to params with "makeoptions_" prefix.
1278  */
1279 void
fixmkoption(void)1280 fixmkoption(void)
1281 {
1282 	struct nvlist *nv;
1283 	char buf[100];
1284 	const char *name;
1285 
1286 	for (nv = mkoptions; nv != NULL; nv = nv->nv_next) {
1287 		snprintf(buf, sizeof(buf), "makeoptions_%s", nv->nv_name);
1288 		name = intern(buf);
1289 		if (!DEFINED_OPTION(name) || !OPT_DEFPARAM(name))
1290 			continue;
1291 		addoption(name, intern(nv->nv_str));
1292 	}
1293 }
1294 
1295 /*
1296  * Add a name=value pair to an option list.  The value may be NULL.
1297  */
1298 static int
do_option(struct hashtab * ht,struct nvlist ** npp,struct nvlist *** next,const char * name,const char * value,const char * type,struct hashtab * stab)1299 do_option(struct hashtab *ht, struct nvlist **npp, struct nvlist ***next,
1300 	  const char *name, const char *value, const char *type,
1301 	  struct hashtab *stab)
1302 {
1303 	struct nvlist *nv, *onv;
1304 
1305 	/* assume it will work */
1306 	nv = newnv(name, value, NULL, 0, NULL);
1307 	if (ht_insert(ht, name, nv) != 0) {
1308 
1309 		/* oops, already got that option - remove it first */
1310 		if ((onv = ht_lookup(ht, name)) == NULL)
1311 			panic("do_option 1");
1312 		if (onv->nv_str != NULL && !OPT_FSOPT(name))
1313 			cfgwarn("already have %s `%s=%s'", type, name,
1314 			    onv->nv_str);
1315 		else
1316 			cfgwarn("already have %s `%s'", type, name);
1317 
1318 		if (undo_option(ht, npp, next, name, type))
1319 			panic("do_option 2");
1320 		if (stab != NULL &&
1321 		    undo_option(stab, NULL, NULL, strtolower(name), type))
1322 			panic("do_option 3");
1323 
1324 		/* now try adding it again */
1325 		if (ht_insert(ht, name, nv) != 0)
1326 			panic("do_option 4");
1327 
1328 		CFGDBG(2, "opt `%s' replaced", name);
1329 	}
1330 	**next = nv;
1331 	*next = &nv->nv_next;
1332 
1333 	return (0);
1334 }
1335 
1336 /*
1337  * Remove a name from a hash table,
1338  * and optionally, a name=value pair from an option list.
1339  */
1340 static int
undo_option(struct hashtab * ht,struct nvlist ** npp,struct nvlist *** next,const char * name,const char * type)1341 undo_option(struct hashtab *ht, struct nvlist **npp,
1342     struct nvlist ***next, const char *name, const char *type)
1343 {
1344 	struct nvlist *nv;
1345 
1346 	if (ht_remove(ht, name)) {
1347 		/*
1348 		 * -U command line option removals are always silent
1349 		 */
1350 		if (!handling_cmdlineopts)
1351 			cfgwarn("%s `%s' is not defined", type, name);
1352 		return (1);
1353 	}
1354 	if (npp == NULL) {
1355 		CFGDBG(2, "opt `%s' deselected", name);
1356 		return (0);
1357 	}
1358 
1359 	for ( ; *npp != NULL; npp = &(*npp)->nv_next) {
1360 		if ((*npp)->nv_name != name)
1361 			continue;
1362 		if (next != NULL && *next == &(*npp)->nv_next)
1363 			*next = npp;
1364 		nv = (*npp)->nv_next;
1365 		CFGDBG(2, "opt `%s' deselected", (*npp)->nv_name);
1366 		nvfree(*npp);
1367 		*npp = nv;
1368 		return (0);
1369 	}
1370 	panic("%s `%s' is not defined in nvlist", type, name);
1371 	return (1);
1372 }
1373 
1374 /*
1375  * Return true if there is at least one instance of the given unit
1376  * on the given device attachment (or any units, if unit == WILD).
1377  */
1378 int
deva_has_instances(struct deva * deva,int unit)1379 deva_has_instances(struct deva *deva, int unit)
1380 {
1381 	struct devi *i;
1382 
1383 	/*
1384 	 * EHAMMERTOOBIG: we shouldn't check i_pseudoroot here.
1385 	 * What we want by this check is them to appear non-present
1386 	 * except for purposes of other devices being able to attach
1387 	 * to them.
1388 	 */
1389 	for (i = deva->d_ihead; i != NULL; i = i->i_asame)
1390 		if (i->i_active == DEVI_ACTIVE && i->i_pseudoroot == 0 &&
1391 		    (unit == WILD || unit == i->i_unit || i->i_unit == STAR))
1392 			return (1);
1393 	return (0);
1394 }
1395 
1396 /*
1397  * Return true if there is at least one instance of the given unit
1398  * on the given base (or any units, if unit == WILD).
1399  */
1400 int
devbase_has_instances(struct devbase * dev,int unit)1401 devbase_has_instances(struct devbase *dev, int unit)
1402 {
1403 	struct deva *da;
1404 
1405 	/*
1406 	 * Pseudo-devices are a little special.  We consider them
1407 	 * to have instances only if they are both:
1408 	 *
1409 	 *	1. Included in this kernel configuration.
1410 	 *
1411 	 *	2. Be declared "defpseudodev".
1412 	 */
1413 	if (dev->d_ispseudo) {
1414 		return ((ht_lookup(devitab, dev->d_name) != NULL)
1415 			&& (dev->d_ispseudo > 1));
1416 	}
1417 
1418 	for (da = dev->d_ahead; da != NULL; da = da->d_bsame)
1419 		if (deva_has_instances(da, unit))
1420 			return (1);
1421 	return (0);
1422 }
1423 
1424 static int
cfcrosscheck(struct config * cf,const char * what,struct nvlist * nv)1425 cfcrosscheck(struct config *cf, const char *what, struct nvlist *nv)
1426 {
1427 	struct devbase *dev;
1428 	struct devi *pd;
1429 	int errs, devunit;
1430 
1431 	if (maxpartitions <= 0)
1432 		panic("cfcrosscheck");
1433 
1434 	for (errs = 0; nv != NULL; nv = nv->nv_next) {
1435 		if (nv->nv_name == NULL)
1436 			continue;
1437 		dev = ht_lookup(devbasetab, nv->nv_name);
1438 		if (dev == NULL)
1439 			panic("cfcrosscheck(%s)", nv->nv_name);
1440 		if (has_attr(dev->d_attrs, s_ifnet))
1441 			devunit = nv->nv_ifunit;	/* XXX XXX XXX */
1442 		else
1443 			devunit = (int)(minor(nv->nv_num) / maxpartitions);
1444 		if (devbase_has_instances(dev, devunit))
1445 			continue;
1446 		if (devbase_has_instances(dev, STAR) &&
1447 		    devunit >= dev->d_umax)
1448 			continue;
1449 		TAILQ_FOREACH(pd, &allpseudo, i_next) {
1450 			if (pd->i_base == dev && devunit < dev->d_umax &&
1451 			    devunit >= 0)
1452 				goto loop;
1453 		}
1454 		(void)fprintf(stderr,
1455 		    "%s:%d: %s says %s on %s, but there's no %s\n",
1456 		    conffile, cf->cf_lineno,
1457 		    cf->cf_name, what, nv->nv_str, nv->nv_str);
1458 		errs++;
1459  loop:
1460 		;
1461 	}
1462 	return (errs);
1463 }
1464 
1465 /*
1466  * Cross-check the configuration: make sure that each target device
1467  * or attribute (`at foo[0*?]') names at least one real device.  Also
1468  * see that the root and dump devices for all configurations are there.
1469  */
1470 int
crosscheck(void)1471 crosscheck(void)
1472 {
1473 	struct config *cf;
1474 	int errs;
1475 
1476 	errs = 0;
1477 	if (TAILQ_EMPTY(&allcf)) {
1478 		warnx("%s has no configurations!", conffile);
1479 		errs++;
1480 	}
1481 	TAILQ_FOREACH(cf, &allcf, cf_next) {
1482 		if (cf->cf_root != NULL) {	/* i.e., not root on ? */
1483 			errs += cfcrosscheck(cf, "root", cf->cf_root);
1484 			errs += cfcrosscheck(cf, "dumps", cf->cf_dump);
1485 		}
1486 	}
1487 	return (errs);
1488 }
1489 
1490 /*
1491  * Check to see if there is a *'d unit with a needs-count file.
1492  */
1493 int
badstar(void)1494 badstar(void)
1495 {
1496 	struct devbase *d;
1497 	struct deva *da;
1498 	struct devi *i;
1499 	int errs, n;
1500 
1501 	errs = 0;
1502 	TAILQ_FOREACH(d, &allbases, d_next) {
1503 		for (da = d->d_ahead; da != NULL; da = da->d_bsame)
1504 			for (i = da->d_ihead; i != NULL; i = i->i_asame) {
1505 				if (i->i_unit == STAR)
1506 					goto aybabtu;
1507 			}
1508 		continue;
1509  aybabtu:
1510 		if (ht_lookup(needcnttab, d->d_name)) {
1511 			warnx("%s's cannot be *'d until its driver is fixed",
1512 			    d->d_name);
1513 			errs++;
1514 			continue;
1515 		}
1516 		for (n = 0; i != NULL; i = i->i_alias)
1517 			if (!i->i_collapsed)
1518 				n++;
1519 		if (n < 1)
1520 			panic("badstar() n<1");
1521 	}
1522 	return (errs);
1523 }
1524 
1525 /*
1526  * Verify/create builddir if necessary, change to it, and verify srcdir.
1527  * This will be called when we see the first include.
1528  */
1529 void
setupdirs(void)1530 setupdirs(void)
1531 {
1532 	struct stat st;
1533 
1534 	/* srcdir must be specified if builddir is not specified or if
1535 	 * no configuration filename was specified. */
1536 	if ((builddir || strcmp(defbuilddir, ".") == 0) && !srcdir) {
1537 		cfgerror("source directory must be specified");
1538 		exit(1);
1539 	}
1540 
1541 	if (Lflag) {
1542 		if (srcdir == NULL)
1543 			srcdir = "../../..";
1544 		return;
1545 	}
1546 
1547 	if (srcdir == NULL)
1548 		srcdir = "../../../..";
1549 	if (builddir == NULL)
1550 		builddir = defbuilddir;
1551 
1552 	if (stat(builddir, &st) == -1) {
1553 		if (mkdir(builddir, 0777) == -1)
1554 			errx(EXIT_FAILURE, "cannot create %s", builddir);
1555 	} else if (!S_ISDIR(st.st_mode))
1556 		errx(EXIT_FAILURE, "%s is not a directory", builddir);
1557 	if (chdir(builddir) == -1)
1558 		err(EXIT_FAILURE, "cannot change to %s", builddir);
1559 	if (stat(srcdir, &st) == -1)
1560 		err(EXIT_FAILURE, "cannot stat %s", srcdir);
1561 	if (!S_ISDIR(st.st_mode))
1562 		errx(EXIT_FAILURE, "%s is not a directory", srcdir);
1563 }
1564 
1565 /*
1566  * Write identifier from "ident" directive into file, for
1567  * newvers.sh to pick it up.
1568  */
1569 int
mkident(void)1570 mkident(void)
1571 {
1572 	FILE *fp;
1573 	int error = 0;
1574 
1575 	(void)unlink("ident");
1576 
1577 	if (ident == NULL)
1578 		return (0);
1579 
1580 	if ((fp = fopen("ident", "w")) == NULL) {
1581 		warn("cannot write ident");
1582 		return (1);
1583 	}
1584 	if (vflag)
1585 		(void)printf("using ident '%s'\n", ident);
1586 	fprintf(fp, "%s\n", ident);
1587 	fflush(fp);
1588 	if (ferror(fp))
1589 		error = 1;
1590 	(void)fclose(fp);
1591 
1592 	return error;
1593 }
1594 
1595 void
logconfig_start(void)1596 logconfig_start(void)
1597 {
1598 	extern FILE *yyin;
1599 	char line[1024];
1600 	const char *tmpdir;
1601 	struct stat st;
1602 	int fd;
1603 
1604 	if (yyin == NULL || fstat(fileno(yyin), &st) == -1)
1605 		return;
1606 	cfgtime = st.st_mtime;
1607 
1608 	tmpdir = getenv("TMPDIR");
1609 	if (tmpdir == NULL)
1610 		tmpdir = _PATH_TMP;
1611 	(void)snprintf(line, sizeof(line), "%s/config.tmp.XXXXXX", tmpdir);
1612 	if ((fd = mkstemp(line)) == -1 ||
1613 	    (cfg = fdopen(fd, "r+")) == NULL) {
1614 		if (fd != -1) {
1615 			(void)unlink(line);
1616 			(void)close(fd);
1617 		}
1618 		cfg = NULL;
1619 		return;
1620 	}
1621 	(void)unlink(line);
1622 
1623 	(void)fprintf(cfg, "#include <sys/cdefs.h>\n\n");
1624 	(void)fprintf(cfg, "#include \"opt_config.h\"\n");
1625 	(void)fprintf(cfg, "\n");
1626 	(void)fprintf(cfg, "/*\n");
1627 	(void)fprintf(cfg, " * Add either (or both) of\n");
1628 	(void)fprintf(cfg, " *\n");
1629 	(void)fprintf(cfg, " *\toptions %s\n", LOGCONFIG_LARGE);
1630 	(void)fprintf(cfg, " *\toptions %s\n", LOGCONFIG_SMALL);
1631 	(void)fprintf(cfg, " *\n");
1632 	(void)fprintf(cfg,
1633 	    " * to your kernel config file to embed it in the resulting\n");
1634 	(void)fprintf(cfg,
1635 	    " * kernel.  The latter option does not include files that are\n");
1636 	(void)fprintf(cfg,
1637 	    " * included (recursively) by your config file.  The embedded\n");
1638 	(void)fprintf(cfg,
1639 	    " * data be extracted by using the command:\n");
1640 	(void)fprintf(cfg, " *\n");
1641 	(void)fprintf(cfg,
1642 	    " *\tstrings netbsd | sed -n 's/^_CFG_//p' | unvis\n");
1643 	(void)fprintf(cfg, " */\n");
1644 	(void)fprintf(cfg, "\n");
1645 	(void)fprintf(cfg, "#ifdef CONFIG_FILE\n");
1646 	(void)fprintf(cfg, "#if defined(%s) || defined(%s)\n\n",
1647 	    LOGCONFIG_LARGE, LOGCONFIG_SMALL);
1648 	(void)fprintf(cfg, "static const char config[] __used =\n\n");
1649 
1650 	(void)fprintf(cfg, "#ifdef %s\n\n", LOGCONFIG_LARGE);
1651 	(void)fprintf(cfg, "\"_CFG_### START CONFIG FILE \\\"%s\\\"\\n\"\n\n",
1652 	    conffile);
1653 	(void)fprintf(cfg, "#endif /* %s */\n\n", LOGCONFIG_LARGE);
1654 
1655 	logconfig_include(yyin, NULL);
1656 
1657 	(void)fprintf(cfg, "#ifdef %s\n\n", LOGCONFIG_LARGE);
1658 	(void)fprintf(cfg, "\"_CFG_### END CONFIG FILE \\\"%s\\\"\\n\"\n",
1659 	    conffile);
1660 
1661 	rewind(yyin);
1662 }
1663 
1664 void
logconfig_include(FILE * cf,const char * filename)1665 logconfig_include(FILE *cf, const char *filename)
1666 {
1667 	char line[1024], in[2048], *out;
1668 	struct stat st;
1669 	int missingeol;
1670 
1671 	if (!cfg)
1672 		return;
1673 
1674 	missingeol = 0;
1675 	if (fstat(fileno(cf), &st) == -1)
1676 		return;
1677 	if (cfgtime < st.st_mtime)
1678 		cfgtime = st.st_mtime;
1679 
1680 	if (filename)
1681 		(void)fprintf(cfg,
1682 		    "\"_CFG_### (included from \\\"%s\\\")\\n\"\n",
1683 		    filename);
1684 	while (fgets(line, sizeof(line), cf) != NULL) {
1685 		missingeol = 1;
1686 		(void)fprintf(cfg, "\"_CFG_");
1687 		if (filename)
1688 			(void)fprintf(cfg, "###> ");
1689 		strvis(in, line, VIS_TAB);
1690 		for (out = in; *out; out++)
1691 			switch (*out) {
1692 			case '\n':
1693 				(void)fprintf(cfg, "\\n\"\n");
1694 				missingeol = 0;
1695 				break;
1696 			case '"': case '\\':
1697 				(void)fputc('\\', cfg);
1698 				/* FALLTHROUGH */
1699 			default:
1700 				(void)fputc(*out, cfg);
1701 				break;
1702 			}
1703 	}
1704 	if (missingeol) {
1705 		(void)fprintf(cfg, "\\n\"\n");
1706 		warnx("%s: newline missing at EOF",
1707 		    filename != NULL ? filename : conffile);
1708 	}
1709 	if (filename)
1710 		(void)fprintf(cfg, "\"_CFG_### (end include \\\"%s\\\")\\n\"\n",
1711 		    filename);
1712 
1713 	rewind(cf);
1714 }
1715 
1716 void
logconfig_end(void)1717 logconfig_end(void)
1718 {
1719 	char line[1024];
1720 	FILE *fp;
1721 	struct stat st;
1722 
1723 	if (!cfg)
1724 		return;
1725 
1726 	(void)fprintf(cfg, "#endif /* %s */\n", LOGCONFIG_LARGE);
1727 	(void)fprintf(cfg, ";\n");
1728 	(void)fprintf(cfg, "#endif /* %s || %s */\n",
1729 	    LOGCONFIG_LARGE, LOGCONFIG_SMALL);
1730 	(void)fprintf(cfg, "#endif /* CONFIG_FILE */\n");
1731 	fflush(cfg);
1732 	if (ferror(cfg))
1733 		err(EXIT_FAILURE, "write to temporary file for config.h failed");
1734 	rewind(cfg);
1735 
1736 	if (stat("config_file.h", &st) != -1) {
1737 		if (cfgtime < st.st_mtime) {
1738 			fclose(cfg);
1739 			return;
1740 		}
1741 	}
1742 
1743 	fp = fopen("config_file.h", "w");
1744 	if (!fp)
1745 		err(EXIT_FAILURE, "cannot open \"config.h\"");
1746 
1747 	while (fgets(line, sizeof(line), cfg) != NULL)
1748 		fputs(line, fp);
1749 	fflush(fp);
1750 	if (ferror(fp))
1751 		err(EXIT_FAILURE, "write to \"config.h\" failed");
1752 	fclose(fp);
1753 	fclose(cfg);
1754 }
1755 
1756 const char *
strtolower(const char * name)1757 strtolower(const char *name)
1758 {
1759 	const char *n;
1760 	char *p, low[500];
1761 	char c;
1762 
1763 	for (n = name, p = low; (c = *n) != '\0'; n++)
1764 		*p++ = (char)(isupper((u_char)c) ? tolower((u_char)c) : c);
1765 	*p = '\0';
1766 	return (intern(low));
1767 }
1768 
1769 static int
is_elf(const char * file)1770 is_elf(const char *file)
1771 {
1772 	int kernel;
1773 	char hdr[4];
1774 
1775 	kernel = open(file, O_RDONLY);
1776 	if (kernel == -1)
1777 		err(EXIT_FAILURE, "cannot open %s", file);
1778 	if (read(kernel, hdr, 4) != 4)
1779 		err(EXIT_FAILURE, "Cannot read from %s", file);
1780 	(void)close(kernel);
1781 
1782 	return memcmp("\177ELF", hdr, 4) == 0 ? 1 : 0;
1783 }
1784 
1785 static int
extract_config(const char * kname,const char * cname,int cfd)1786 extract_config(const char *kname, const char *cname, int cfd)
1787 {
1788 	char *ptr;
1789 	void *base;
1790 	int found, kfd;
1791 	struct stat st;
1792 	off_t i;
1793 
1794 	found = 0;
1795 
1796 	/* mmap(2) binary kernel */
1797 	kfd = open(conffile, O_RDONLY);
1798 	if (kfd == -1)
1799 		err(EXIT_FAILURE, "cannot open %s", kname);
1800 	if (fstat(kfd, &st) == -1)
1801 		err(EXIT_FAILURE, "cannot stat %s", kname);
1802 	base = mmap(0, (size_t)st.st_size, PROT_READ, MAP_FILE | MAP_SHARED,
1803 	    kfd, 0);
1804 	if (base == MAP_FAILED)
1805 		err(EXIT_FAILURE, "cannot mmap %s", kname);
1806 	ptr = base;
1807 
1808 	/* Scan mmap(2)'ed region, extracting kernel configuration */
1809 	for (i = 0; i < st.st_size; i++) {
1810 		if ((*ptr == '_') && (st.st_size - i > 5) && memcmp(ptr,
1811 		    "_CFG_", 5) == 0) {
1812 			/* Line found */
1813 			char *oldptr, line[LINE_MAX + 1], uline[LINE_MAX + 1];
1814 			int j;
1815 
1816 			found = 1;
1817 
1818 			oldptr = (ptr += 5);
1819 			while (*ptr != '\n' && *ptr != '\0')
1820 				ptr++;
1821 			if (ptr - oldptr > LINE_MAX)
1822 				errx(EXIT_FAILURE, "line too long");
1823 			i += ptr - oldptr + 5;
1824 			(void)memcpy(line, oldptr, (size_t)(ptr - oldptr));
1825 			line[ptr - oldptr] = '\0';
1826 			j = strunvis(uline, line);
1827 			if (j == -1)
1828 				errx(EXIT_FAILURE, "unvis: invalid "
1829 				    "encoded sequence");
1830 			uline[j] = '\n';
1831 			if (write(cfd, uline, (size_t)j + 1) == -1)
1832 				err(EXIT_FAILURE, "cannot write to %s", cname);
1833 		} else
1834 			ptr++;
1835 	}
1836 
1837 	(void)close(kfd);
1838 	(void)munmap(base, (size_t)st.st_size);
1839 
1840 	return found;
1841 }
1842 
1843 struct dhdi_params {
1844 	struct devbase *d;
1845 	int unit;
1846 	int level;
1847 };
1848 
1849 static int
devbase_has_dead_instances(const char * key,void * value,void * aux)1850 devbase_has_dead_instances(const char *key, void *value, void *aux)
1851 {
1852 	struct devi *i;
1853 	struct dhdi_params *dhdi = aux;
1854 
1855 	for (i = value; i != NULL; i = i->i_alias)
1856 		if (i->i_base == dhdi->d &&
1857 		    (dhdi->unit == WILD || dhdi->unit == i->i_unit ||
1858 		     i->i_unit == STAR) &&
1859 		    i->i_level >= dhdi->level)
1860 			return 1;
1861 	return 0;
1862 }
1863 
1864 /*
1865  * This is almost the same as devbase_has_instances, except it
1866  * may have special considerations regarding ignored instances.
1867  */
1868 
1869 static int
devbase_has_any_instance(struct devbase * dev,int unit,int state,int level)1870 devbase_has_any_instance(struct devbase *dev, int unit, int state, int level)
1871 {
1872 	struct deva *da;
1873 	struct devi *i;
1874 
1875 	if (dev->d_ispseudo) {
1876 		if (dev->d_ihead != NULL)
1877 			return 1;
1878 		else if (state != DEVI_IGNORED)
1879 			return 0;
1880 		if ((i = ht_lookup(deaddevitab, dev->d_name)) == NULL)
1881 			return 0;
1882 		return (i->i_level >= level);
1883 	}
1884 
1885 	for (da = dev->d_ahead; da != NULL; da = da->d_bsame)
1886 		for (i = da->d_ihead; i != NULL; i = i->i_asame)
1887 			if ((i->i_active == DEVI_ACTIVE ||
1888 			     i->i_active == state) &&
1889 			    (unit == WILD || unit == i->i_unit ||
1890 			     i->i_unit == STAR))
1891 				return 1;
1892 
1893 	if (state == DEVI_IGNORED) {
1894 		struct dhdi_params dhdi = { dev, unit, level };
1895 		/* also check dead devices */
1896 		return ht_enumerate(deaddevitab, devbase_has_dead_instances,
1897 		    &dhdi);
1898 	}
1899 
1900 	return 0;
1901 }
1902 
1903 /*
1904  * check_dead_devi(), used with ht_enumerate, checks if any of the removed
1905  * device instances would have been a valid instance considering the devbase,
1906  * the parent device and the interface attribute.
1907  *
1908  * In other words, for a non-active device, it checks if children would be
1909  * actual orphans or the result of a negative statement in the config file.
1910  */
1911 
1912 struct cdd_params {
1913 	struct devbase *d;
1914 	struct attr *at;
1915 	struct devbase *parent;
1916 };
1917 
1918 static int
check_dead_devi(const char * key,void * value,void * aux)1919 check_dead_devi(const char *key, void *value, void *aux)
1920 {
1921 	struct cdd_params *cdd = aux;
1922 	struct devi *i = value;
1923 	struct pspec *p;
1924 
1925 	if (i->i_base != cdd->d)
1926 		return 0;
1927 
1928 	for (; i != NULL; i = i->i_alias) {
1929 		p = i->i_pspec;
1930 		if ((p == NULL && cdd->at == NULL) ||
1931 		    (p != NULL && p->p_iattr == cdd->at &&
1932 		     (p->p_atdev == NULL || p->p_atdev == cdd->parent))) {
1933 			if (p != NULL &&
1934 			    !devbase_has_any_instance(cdd->parent, p->p_atunit,
1935 			    DEVI_IGNORED, i->i_level))
1936 				return 0;
1937 			else
1938 				return 1;
1939 		}
1940 	}
1941 	return 0;
1942 }
1943 
1944 static void
do_kill_orphans(struct devbase * d,struct attr * at,struct devbase * parent,int state)1945 do_kill_orphans(struct devbase *d, struct attr *at, struct devbase *parent,
1946     int state)
1947 {
1948 	struct nvlist *nv1;
1949 	struct attrlist *al;
1950 	struct attr *a;
1951 	struct devi *i, *j = NULL;
1952 	struct pspec *p;
1953 	int active = 0;
1954 
1955 	/*
1956 	 * A pseudo-device will always attach at root, and if it has an
1957 	 * instance (it cannot have more than one), it is enough to consider
1958 	 * it active, as there is no real attachment.
1959 	 *
1960 	 * A pseudo device can never be marked DEVI_IGNORED.
1961 	 */
1962 	if (d->d_ispseudo) {
1963 		if (d->d_ihead != NULL)
1964 			d->d_ihead->i_active = active = DEVI_ACTIVE;
1965 		else {
1966 			if (ht_lookup(deaddevitab, d->d_name) != NULL)
1967 				active = DEVI_IGNORED;
1968 			else
1969 				return;
1970 		}
1971 	} else {
1972 		int seen = 0;
1973 
1974 		for (i = d->d_ihead; i != NULL; i = i->i_bsame) {
1975 			for (j = i; j != NULL; j = j->i_alias) {
1976 				p = j->i_pspec;
1977 				if ((p == NULL && at == NULL) ||
1978 				    (p != NULL && p->p_iattr == at &&
1979 				    (p->p_atdev == NULL ||
1980 				    p->p_atdev == parent))) {
1981 					if (p != NULL &&
1982 					    !devbase_has_any_instance(parent,
1983 					      p->p_atunit, state, j->i_level))
1984 						continue;
1985 					/*
1986 					 * There are Fry-like devices which can
1987 					 * be their own grand-parent (or even
1988 					 * parent, like uhub).  We don't want
1989 					 * to loop, so if we've already reached
1990 					 * an instance for one reason or
1991 					 * another, stop there.
1992 					 */
1993 					if (j->i_active == DEVI_ACTIVE ||
1994 					    j->i_active == state) {
1995 						/*
1996 						 * Device has already been
1997 						 * seen.  However it might
1998 						 * have siblings who still
1999 						 * have to be activated or
2000 						 * orphaned.
2001 						 */
2002 						seen = 1;
2003 						continue;
2004 					}
2005 					j->i_active = active = state;
2006 					if (p != NULL)
2007 						p->p_active = state;
2008 				}
2009 			}
2010 		}
2011 		/*
2012 		 * If we've been there but have made no change, stop.
2013 		 */
2014 		if (seen && !active)
2015 			return;
2016 		if (!active) {
2017 			struct cdd_params cdd = { d, at, parent };
2018 			/* Look for a matching dead devi */
2019 			if (ht_enumerate(deaddevitab, check_dead_devi, &cdd) &&
2020 			    d != parent)
2021 				/*
2022 				 * That device had its instances removed.
2023 				 * Continue the loop marking descendants
2024 				 * with DEVI_IGNORED instead of DEVI_ACTIVE.
2025 				 *
2026 				 * There is one special case for devices that
2027 				 * are their own parent:  if that instance is
2028 				 * removed (e.g., no uhub* at uhub?), we don't
2029 				 * have to continue looping.
2030 				 */
2031 				active = DEVI_IGNORED;
2032 			else
2033 				return;
2034 		}
2035 	}
2036 
2037 	for (al = d->d_attrs; al != NULL; al = al->al_next) {
2038 		a = al->al_this;
2039 		for (nv1 = a->a_devs; nv1 != NULL; nv1 = nv1->nv_next)
2040 			do_kill_orphans(nv1->nv_ptr, a, d, active);
2041 	}
2042 }
2043 
2044 static int
2045 /*ARGSUSED*/
kill_orphans_cb(const char * key,void * value,void * aux)2046 kill_orphans_cb(const char *key, void *value, void *aux)
2047 {
2048 	do_kill_orphans((struct devbase *)value, NULL, NULL, DEVI_ACTIVE);
2049 	return 0;
2050 }
2051 
2052 static void
kill_orphans(void)2053 kill_orphans(void)
2054 {
2055 	ht_enumerate(devroottab, kill_orphans_cb, NULL);
2056 }
2057 
2058 static void
add_makeopt(const char * opt)2059 add_makeopt(const char *opt)
2060 {
2061 	struct nvlist *p;
2062 	char *buf = estrdup(opt);
2063 	char *eq = strchr(buf, '=');
2064 
2065 	if (!eq)
2066 		errx(EXIT_FAILURE, "-D %s is not in var=value format", opt);
2067 
2068 	*eq = 0;
2069 	p = newnv(estrdup(buf), estrdup(eq+1), NULL, 0, NULL);
2070 	free(buf);
2071 	p->nv_next = cmdlinedefs;
2072 	cmdlinedefs = p;
2073 }
2074 
2075 static void
remove_makeopt(const char * opt)2076 remove_makeopt(const char *opt)
2077 {
2078 	struct nvlist *p;
2079 
2080 	p = newnv(estrdup(opt), NULL, NULL, 0, NULL);
2081 	p->nv_next = cmdlineundefs;
2082 	cmdlineundefs = p;
2083 }
2084 
2085 static void
handle_cmdline_makeoptions(void)2086 handle_cmdline_makeoptions(void)
2087 {
2088 	struct nvlist *p, *n;
2089 
2090 	handling_cmdlineopts = 1;
2091 	for (p = cmdlineundefs; p; p = n) {
2092 		n = p->nv_next;
2093 		delmkoption(intern(p->nv_name));
2094 		free(__UNCONST(p->nv_name));
2095 		nvfree(p);
2096 	}
2097 	for (p = cmdlinedefs; p; p = n) {
2098 		const char *name = intern(p->nv_name);
2099 
2100 		n = p->nv_next;
2101 		delmkoption(name);
2102 		addmkoption(name, intern(p->nv_str));
2103 		free(__UNCONST(p->nv_name));
2104 		free(__UNCONST(p->nv_str));
2105 
2106 		nvfree(p);
2107 	}
2108 	handling_cmdlineopts = 0;
2109 }
2110