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