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