1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1980, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 #ifndef lint
33 static const char copyright[] =
34 "@(#) Copyright (c) 1980, 1993\n\
35 	The Regents of the University of California.  All rights reserved.\n";
36 #endif /* not lint */
37 
38 #ifndef lint
39 #if 0
40 static char sccsid[] = "@(#)main.c	8.1 (Berkeley) 6/6/93";
41 #endif
42 static const char rcsid[] =
43   "$FreeBSD: stable/12/usr.sbin/config/main.c 360368 2020-04-27 05:35:26Z jah $";
44 #endif /* not lint */
45 
46 #include <sys/types.h>
47 #include <sys/stat.h>
48 #include <sys/sbuf.h>
49 #include <sys/file.h>
50 #include <sys/mman.h>
51 #include <sys/param.h>
52 
53 #include <assert.h>
54 #include <ctype.h>
55 #include <err.h>
56 #include <stdio.h>
57 #include <string.h>
58 #include <sysexits.h>
59 #include <unistd.h>
60 #include <dirent.h>
61 #include "y.tab.h"
62 #include "config.h"
63 #include "configvers.h"
64 
65 #ifndef TRUE
66 #define TRUE	(1)
67 #endif
68 
69 #ifndef FALSE
70 #define FALSE	(0)
71 #endif
72 
73 #define	CDIR	"../compile/"
74 
75 char	*machinename;
76 char	*machinearch;
77 
78 struct cfgfile_head	cfgfiles;
79 struct cputype_head	cputype;
80 struct opt_head		opt, mkopt, rmopts;
81 struct opt_list_head	otab;
82 struct envvar_head	envvars;
83 struct hint_head	hints;
84 struct includepath_head	includepath;
85 
86 char *	PREFIX;
87 char 	destdir[MAXPATHLEN];
88 char 	srcdir[MAXPATHLEN];
89 
90 int	debugging;
91 int	profiling;
92 int	found_defaults;
93 int	incignore;
94 
95 /*
96  * Preserve old behaviour in INCLUDE_CONFIG_FILE handling (files are included
97  * literally).
98  */
99 int	filebased = 0;
100 int	versreq;
101 
102 static void configfile(void);
103 static void get_srcdir(void);
104 static void usage(void);
105 static void cleanheaders(char *);
106 static void kernconfdump(const char *);
107 static void badversion(void);
108 static void checkversion(void);
109 extern int yyparse(void);
110 
111 struct hdr_list {
112 	char *h_name;
113 	struct hdr_list *h_next;
114 } *htab;
115 
116 static struct sbuf *line_buf = NULL;
117 
118 /*
119  * Config builds a set of files for building a UNIX
120  * system given a description of the desired system.
121  */
122 int
main(int argc,char ** argv)123 main(int argc, char **argv)
124 {
125 
126 	struct stat buf;
127 	int ch, len;
128 	char *p;
129 	char *kernfile;
130 	struct includepath* ipath;
131 	int printmachine;
132 
133 	printmachine = 0;
134 	kernfile = NULL;
135 	SLIST_INIT(&includepath);
136 	while ((ch = getopt(argc, argv, "CI:d:gmps:Vx:")) != -1)
137 		switch (ch) {
138 		case 'C':
139 			filebased = 1;
140 			break;
141 		case 'I':
142 			ipath = (struct includepath *) \
143 			    	calloc(1, sizeof (struct includepath));
144 			if (ipath == NULL)
145 				err(EXIT_FAILURE, "calloc");
146 			ipath->path = optarg;
147 			SLIST_INSERT_HEAD(&includepath, ipath, path_next);
148 			break;
149 		case 'm':
150 			printmachine = 1;
151 			break;
152 		case 'd':
153 			if (*destdir == '\0')
154 				strlcpy(destdir, optarg, sizeof(destdir));
155 			else
156 				errx(EXIT_FAILURE, "directory already set");
157 			break;
158 		case 'g':
159 			debugging++;
160 			break;
161 		case 'p':
162 			profiling++;
163 			break;
164 		case 's':
165 			if (*srcdir == '\0')
166 				strlcpy(srcdir, optarg, sizeof(srcdir));
167 			else
168 				errx(EXIT_FAILURE, "src directory already set");
169 			break;
170 		case 'V':
171 			printf("%d\n", CONFIGVERS);
172 			exit(0);
173 		case 'x':
174 			kernfile = optarg;
175 			break;
176 		case '?':
177 		default:
178 			usage();
179 		}
180 	argc -= optind;
181 	argv += optind;
182 
183 	if (kernfile != NULL) {
184 		kernconfdump(kernfile);
185 		exit(EXIT_SUCCESS);
186 	}
187 
188 	if (argc != 1)
189 		usage();
190 
191 	PREFIX = *argv;
192 	if (stat(PREFIX, &buf) != 0 || !S_ISREG(buf.st_mode))
193 		err(2, "%s", PREFIX);
194 	if (freopen("DEFAULTS", "r", stdin) != NULL) {
195 		found_defaults = 1;
196 		yyfile = "DEFAULTS";
197 	} else {
198 		if (freopen(PREFIX, "r", stdin) == NULL)
199 			err(2, "%s", PREFIX);
200 		yyfile = PREFIX;
201 	}
202 	if (*destdir != '\0') {
203 		len = strlen(destdir);
204 		while (len > 1 && destdir[len - 1] == '/')
205 			destdir[--len] = '\0';
206 		if (*srcdir == '\0')
207 			get_srcdir();
208 	} else {
209 		strlcpy(destdir, CDIR, sizeof(destdir));
210 		strlcat(destdir, PREFIX, sizeof(destdir));
211 	}
212 
213 	SLIST_INIT(&cputype);
214 	SLIST_INIT(&mkopt);
215 	SLIST_INIT(&opt);
216 	SLIST_INIT(&rmopts);
217 	STAILQ_INIT(&cfgfiles);
218 	STAILQ_INIT(&dtab);
219 	STAILQ_INIT(&fntab);
220 	STAILQ_INIT(&ftab);
221 	STAILQ_INIT(&hints);
222 	STAILQ_INIT(&envvars);
223 	if (yyparse())
224 		exit(3);
225 
226 	/*
227 	 * Ensure that required elements (machine, cpu, ident) are present.
228 	 */
229 	if (machinename == NULL) {
230 		printf("Specify machine type, e.g. ``machine i386''\n");
231 		exit(1);
232 	}
233 	if (ident == NULL) {
234 		printf("no ident line specified\n");
235 		exit(1);
236 	}
237 	if (SLIST_EMPTY(&cputype)) {
238 		printf("cpu type must be specified\n");
239 		exit(1);
240 	}
241 	checkversion();
242 
243 	if (printmachine) {
244 		printf("%s\t%s\n",machinename,machinearch);
245 		exit(0);
246 	}
247 
248 	/* Make compile directory */
249 	p = path((char *)NULL);
250 	if (stat(p, &buf)) {
251 		if (mkdir(p, 0777))
252 			err(2, "%s", p);
253 	} else if (!S_ISDIR(buf.st_mode))
254 		errx(EXIT_FAILURE, "%s isn't a directory", p);
255 
256 	configfile();			/* put config file into kernel*/
257 	options();			/* make options .h files */
258 	makefile();			/* build Makefile */
259 	makeenv();			/* build env.c */
260 	makehints();			/* build hints.c */
261 	headers();			/* make a lot of .h files */
262 	cleanheaders(p);
263 	printf("Kernel build directory is %s\n", p);
264 	printf("Don't forget to do ``make cleandepend && make depend''\n");
265 	exit(0);
266 }
267 
268 /*
269  * get_srcdir
270  *	determine the root of the kernel source tree
271  *	and save that in srcdir.
272  */
273 static void
get_srcdir(void)274 get_srcdir(void)
275 {
276 	struct stat lg, phy;
277 	char *p, *pwd;
278 	int i;
279 
280 	if (realpath("../..", srcdir) == NULL)
281 		err(EXIT_FAILURE, "Unable to find root of source tree");
282 	if ((pwd = getenv("PWD")) != NULL && *pwd == '/' &&
283 	    (pwd = strdup(pwd)) != NULL) {
284 		/* Remove the last two path components. */
285 		for (i = 0; i < 2; i++) {
286 			if ((p = strrchr(pwd, '/')) == NULL) {
287 				free(pwd);
288 				return;
289 			}
290 			*p = '\0';
291 		}
292 		if (stat(pwd, &lg) != -1 && stat(srcdir, &phy) != -1 &&
293 		    lg.st_dev == phy.st_dev && lg.st_ino == phy.st_ino)
294 			strlcpy(srcdir, pwd, MAXPATHLEN);
295 		free(pwd);
296 	}
297 }
298 
299 static void
usage(void)300 usage(void)
301 {
302 
303 	fprintf(stderr,
304 	    "usage: config [-CgmpV] [-d destdir] [-s srcdir] sysname\n");
305 	fprintf(stderr, "       config -x kernel\n");
306 	exit(EX_USAGE);
307 }
308 
309 static void
init_line_buf(void)310 init_line_buf(void)
311 {
312 	if (line_buf == NULL) {
313 		line_buf = sbuf_new(NULL, NULL, 80, SBUF_AUTOEXTEND);
314 		if (line_buf == NULL) {
315 			errx(EXIT_FAILURE, "failed to allocate line buffer");
316 		}
317 	} else {
318 		sbuf_clear(line_buf);
319 	}
320 }
321 
322 static char *
get_line_buf(void)323 get_line_buf(void)
324 {
325 	if (sbuf_finish(line_buf) != 0) {
326 		errx(EXIT_FAILURE, "failed to generate line buffer, "
327 		    "partial line = %s", sbuf_data(line_buf));
328 	}
329 	return sbuf_data(line_buf);
330 }
331 
332 /*
333  * get_word
334  *	returns EOF on end of file
335  *	NULL on end of line
336  *	pointer to the word otherwise
337  */
338 char *
get_word(FILE * fp)339 get_word(FILE *fp)
340 {
341 	int ch;
342 	int escaped_nl = 0;
343 
344 	init_line_buf();
345 begin:
346 	while ((ch = getc(fp)) != EOF)
347 		if (ch != ' ' && ch != '\t')
348 			break;
349 	if (ch == EOF)
350 		return ((char *)EOF);
351 	if (ch == '\\'){
352 		escaped_nl = 1;
353 		goto begin;
354 	}
355 	if (ch == '\n') {
356 		if (escaped_nl){
357 			escaped_nl = 0;
358 			goto begin;
359 		}
360 		else
361 			return (NULL);
362 	}
363 	sbuf_putc(line_buf, ch);
364 	/* Negation operator is a word by itself. */
365 	if (ch == '!') {
366 		return get_line_buf();
367 	}
368 	while ((ch = getc(fp)) != EOF) {
369 		if (isspace(ch))
370 			break;
371 		sbuf_putc(line_buf, ch);
372 	}
373 	if (ch == EOF)
374 		return ((char *)EOF);
375 	(void) ungetc(ch, fp);
376 	return (get_line_buf());
377 }
378 
379 /*
380  * get_quoted_word
381  *	like get_word but will accept something in double or single quotes
382  *	(to allow embedded spaces).
383  */
384 char *
get_quoted_word(FILE * fp)385 get_quoted_word(FILE *fp)
386 {
387 	int ch;
388 	int escaped_nl = 0;
389 
390 	init_line_buf();
391 begin:
392 	while ((ch = getc(fp)) != EOF)
393 		if (ch != ' ' && ch != '\t')
394 			break;
395 	if (ch == EOF)
396 		return ((char *)EOF);
397 	if (ch == '\\'){
398 		escaped_nl = 1;
399 		goto begin;
400 	}
401 	if (ch == '\n') {
402 		if (escaped_nl){
403 			escaped_nl = 0;
404 			goto begin;
405 		}
406 		else
407 			return (NULL);
408 	}
409 	if (ch == '"' || ch == '\'') {
410 		int quote = ch;
411 
412 		escaped_nl = 0;
413 		while ((ch = getc(fp)) != EOF) {
414 			if (ch == quote && !escaped_nl)
415 				break;
416 			if (ch == '\n' && !escaped_nl) {
417 				printf("config: missing quote reading `%s'\n",
418 					get_line_buf());
419 				exit(2);
420 			}
421 			if (ch == '\\' && !escaped_nl) {
422 				escaped_nl = 1;
423 				continue;
424 			}
425 			if (ch != quote && escaped_nl)
426 				sbuf_putc(line_buf, '\\');
427 			sbuf_putc(line_buf, ch);
428 			escaped_nl = 0;
429 		}
430 	} else {
431 		sbuf_putc(line_buf, ch);
432 		while ((ch = getc(fp)) != EOF) {
433 			if (isspace(ch))
434 				break;
435 			sbuf_putc(line_buf, ch);
436 		}
437 		if (ch != EOF)
438 			(void) ungetc(ch, fp);
439 	}
440 	if (ch == EOF)
441 		return ((char *)EOF);
442 	return (get_line_buf());
443 }
444 
445 /*
446  * prepend the path to a filename
447  */
448 char *
path(const char * file)449 path(const char *file)
450 {
451 	char *cp = NULL;
452 
453 	if (file)
454 		asprintf(&cp, "%s/%s", destdir, file);
455 	else
456 		cp = strdup(destdir);
457 	return (cp);
458 }
459 
460 /*
461  * Generate configuration file based on actual settings. With this mode, user
462  * will be able to obtain and build conifguration file with one command.
463  */
464 static void
configfile_dynamic(struct sbuf * sb)465 configfile_dynamic(struct sbuf *sb)
466 {
467 	struct cputype *cput;
468 	struct device *d;
469 	struct opt *ol;
470 	char *lend;
471 	unsigned int i;
472 
473 	asprintf(&lend, "\\n\\\n");
474 	assert(lend != NULL);
475 	sbuf_printf(sb, "options\t%s%s", OPT_AUTOGEN, lend);
476 	sbuf_printf(sb, "ident\t%s%s", ident, lend);
477 	sbuf_printf(sb, "machine\t%s%s", machinename, lend);
478 	SLIST_FOREACH(cput, &cputype, cpu_next)
479 		sbuf_printf(sb, "cpu\t%s%s", cput->cpu_name, lend);
480 	SLIST_FOREACH(ol, &mkopt, op_next)
481 		sbuf_printf(sb, "makeoptions\t%s=%s%s", ol->op_name,
482 		    ol->op_value, lend);
483 	SLIST_FOREACH(ol, &opt, op_next) {
484 		if (strncmp(ol->op_name, "DEV_", 4) == 0)
485 			continue;
486 		sbuf_printf(sb, "options\t%s", ol->op_name);
487 		if (ol->op_value != NULL) {
488 			sbuf_putc(sb, '=');
489 			for (i = 0; i < strlen(ol->op_value); i++) {
490 				if (ol->op_value[i] == '"')
491 					sbuf_printf(sb, "\\%c",
492 					    ol->op_value[i]);
493 				else
494 					sbuf_printf(sb, "%c",
495 					    ol->op_value[i]);
496 			}
497 			sbuf_printf(sb, "%s", lend);
498 		} else {
499 			sbuf_printf(sb, "%s", lend);
500 		}
501 	}
502 	/*
503 	 * Mark this file as containing everything we need.
504 	 */
505 	STAILQ_FOREACH(d, &dtab, d_next)
506 		sbuf_printf(sb, "device\t%s%s", d->d_name, lend);
507 	free(lend);
508 }
509 
510 /*
511  * Generate file from the configuration files.
512  */
513 static void
configfile_filebased(struct sbuf * sb)514 configfile_filebased(struct sbuf *sb)
515 {
516 	FILE *cff;
517 	struct cfgfile *cf;
518 	int i;
519 
520 	/*
521 	 * Try to read all configuration files. Since those will be present as
522 	 * C string in the macro, we have to slash their ends then the line
523 	 * wraps.
524 	 */
525 	STAILQ_FOREACH(cf, &cfgfiles, cfg_next) {
526 		cff = fopen(cf->cfg_path, "r");
527 		if (cff == NULL) {
528 			warn("Couldn't open file %s", cf->cfg_path);
529 			continue;
530 		}
531 		while ((i = getc(cff)) != EOF) {
532 			if (i == '\n')
533 				sbuf_printf(sb, "\\n\\\n");
534 			else if (i == '"' || i == '\'')
535 				sbuf_printf(sb, "\\%c", i);
536 			else
537 				sbuf_putc(sb, i);
538 		}
539 		fclose(cff);
540 	}
541 }
542 
543 static void
configfile(void)544 configfile(void)
545 {
546 	FILE *fo;
547 	struct sbuf *sb;
548 	char *p;
549 
550 	/* Add main configuration file to the list of files to be included */
551 	cfgfile_add(PREFIX);
552 	p = path("config.c.new");
553 	fo = fopen(p, "w");
554 	if (!fo)
555 		err(2, "%s", p);
556 	sb = sbuf_new(NULL, NULL, 2048, SBUF_AUTOEXTEND);
557 	assert(sb != NULL);
558 	sbuf_clear(sb);
559 	if (filebased) {
560 		/* Is needed, can be used for backward compatibility. */
561 		configfile_filebased(sb);
562 	} else {
563 		configfile_dynamic(sb);
564 	}
565 	sbuf_finish(sb);
566 	/*
567 	 * We print first part of the template, replace our tag with
568 	 * configuration files content and later continue writing our
569 	 * template.
570 	 */
571 	p = strstr(kernconfstr, KERNCONFTAG);
572 	if (p == NULL)
573 		errx(EXIT_FAILURE, "Something went terribly wrong!");
574 	*p = '\0';
575 	fprintf(fo, "%s", kernconfstr);
576 	fprintf(fo, "%s", sbuf_data(sb));
577 	p += strlen(KERNCONFTAG);
578 	fprintf(fo, "%s", p);
579 	sbuf_delete(sb);
580 	fclose(fo);
581 	moveifchanged(path("config.c.new"), path("config.c"));
582 	cfgfile_removeall();
583 }
584 
585 /*
586  * moveifchanged --
587  *	compare two files; rename if changed.
588  */
589 void
moveifchanged(const char * from_name,const char * to_name)590 moveifchanged(const char *from_name, const char *to_name)
591 {
592 	char *p, *q;
593 	int changed;
594 	size_t tsize;
595 	struct stat from_sb, to_sb;
596 	int from_fd, to_fd;
597 
598 	changed = 0;
599 
600 	if ((from_fd = open(from_name, O_RDONLY)) < 0)
601 		err(EX_OSERR, "moveifchanged open(%s)", from_name);
602 
603 	if ((to_fd = open(to_name, O_RDONLY)) < 0)
604 		changed++;
605 
606 	if (!changed && fstat(from_fd, &from_sb) < 0)
607 		err(EX_OSERR, "moveifchanged fstat(%s)", from_name);
608 
609 	if (!changed && fstat(to_fd, &to_sb) < 0)
610 		err(EX_OSERR, "moveifchanged fstat(%s)", to_name);
611 
612 	if (!changed && from_sb.st_size != to_sb.st_size)
613 		changed++;
614 
615 	tsize = (size_t)from_sb.st_size;
616 
617 	if (!changed) {
618 		p = mmap(NULL, tsize, PROT_READ, MAP_SHARED, from_fd, (off_t)0);
619 		if (p == MAP_FAILED)
620 			err(EX_OSERR, "mmap %s", from_name);
621 		q = mmap(NULL, tsize, PROT_READ, MAP_SHARED, to_fd, (off_t)0);
622 		if (q == MAP_FAILED)
623 			err(EX_OSERR, "mmap %s", to_name);
624 
625 		changed = memcmp(p, q, tsize);
626 		munmap(p, tsize);
627 		munmap(q, tsize);
628 	}
629 	if (changed) {
630 		if (rename(from_name, to_name) < 0)
631 			err(EX_OSERR, "rename(%s, %s)", from_name, to_name);
632 	} else {
633 		if (unlink(from_name) < 0)
634 			err(EX_OSERR, "unlink(%s)", from_name);
635 	}
636 }
637 
638 static void
cleanheaders(char * p)639 cleanheaders(char *p)
640 {
641 	DIR *dirp;
642 	struct dirent *dp;
643 	struct file_list *fl;
644 	struct hdr_list *hl;
645 	size_t len;
646 
647 	remember("y.tab.h");
648 	remember("setdefs.h");
649 	STAILQ_FOREACH(fl, &ftab, f_next)
650 		remember(fl->f_fn);
651 
652 	/*
653 	 * Scan the build directory and clean out stuff that looks like
654 	 * it might have been a leftover NFOO header, etc.
655 	 */
656 	if ((dirp = opendir(p)) == NULL)
657 		err(EX_OSERR, "opendir %s", p);
658 	while ((dp = readdir(dirp)) != NULL) {
659 		len = strlen(dp->d_name);
660 		/* Skip non-headers */
661 		if (len < 2 || dp->d_name[len - 2] != '.' ||
662 		    dp->d_name[len - 1] != 'h')
663 			continue;
664 		/* Skip special stuff, eg: bus_if.h, but check opt_*.h */
665 		if (strchr(dp->d_name, '_') &&
666 		    strncmp(dp->d_name, "opt_", 4) != 0)
667 			continue;
668 		/* Check if it is a target file */
669 		for (hl = htab; hl != NULL; hl = hl->h_next) {
670 			if (eq(dp->d_name, hl->h_name)) {
671 				break;
672 			}
673 		}
674 		if (hl)
675 			continue;
676 		printf("Removing stale header: %s\n", dp->d_name);
677 		if (unlink(path(dp->d_name)) == -1)
678 			warn("unlink %s", dp->d_name);
679 	}
680 	(void)closedir(dirp);
681 }
682 
683 void
remember(const char * file)684 remember(const char *file)
685 {
686 	char *s;
687 	struct hdr_list *hl;
688 
689 	if ((s = strrchr(file, '/')) != NULL)
690 		s = ns(s + 1);
691 	else
692 		s = ns(file);
693 
694 	if (strchr(s, '_') && strncmp(s, "opt_", 4) != 0) {
695 		free(s);
696 		return;
697 	}
698 	for (hl = htab; hl != NULL; hl = hl->h_next) {
699 		if (eq(s, hl->h_name)) {
700 			free(s);
701 			return;
702 		}
703 	}
704 	hl = calloc(1, sizeof(*hl));
705 	if (hl == NULL)
706 		err(EXIT_FAILURE, "calloc");
707 	hl->h_name = s;
708 	hl->h_next = htab;
709 	htab = hl;
710 }
711 
712 /*
713  * This one is quick hack. Will be probably moved to elf(3) interface.
714  * It takes kernel configuration file name, passes it as an argument to
715  * elfdump -a, which output is parsed by some UNIX tools...
716  */
717 static void
kernconfdump(const char * file)718 kernconfdump(const char *file)
719 {
720 	struct stat st;
721 	FILE *fp, *pp;
722 	int error, osz, r;
723 	unsigned int i, off, size, t1, t2, align;
724 	char *cmd, *o;
725 
726 	r = open(file, O_RDONLY);
727 	if (r == -1)
728 		err(EXIT_FAILURE, "Couldn't open file '%s'", file);
729 	error = fstat(r, &st);
730 	if (error == -1)
731 		err(EXIT_FAILURE, "fstat() failed");
732 	if (S_ISDIR(st.st_mode))
733 		errx(EXIT_FAILURE, "'%s' is a directory", file);
734 	fp = fdopen(r, "r");
735 	if (fp == NULL)
736 		err(EXIT_FAILURE, "fdopen() failed");
737 	osz = 1024;
738 	o = calloc(1, osz);
739 	if (o == NULL)
740 		err(EXIT_FAILURE, "Couldn't allocate memory");
741 	/* ELF note section header. */
742 	asprintf(&cmd, "/usr/bin/elfdump -c %s | grep -A 8 kern_conf"
743 	    "| tail -5 | cut -d ' ' -f 2 | paste - - - - -", file);
744 	if (cmd == NULL)
745 		errx(EXIT_FAILURE, "asprintf() failed");
746 	pp = popen(cmd, "r");
747 	if (pp == NULL)
748 		errx(EXIT_FAILURE, "popen() failed");
749 	free(cmd);
750 	(void)fread(o, osz, 1, pp);
751 	pclose(pp);
752 	r = sscanf(o, "%d%d%d%d%d", &off, &size, &t1, &t2, &align);
753 	free(o);
754 	if (r != 5)
755 		errx(EXIT_FAILURE, "File %s doesn't contain configuration "
756 		    "file. Either unsupported, or not compiled with "
757 		    "INCLUDE_CONFIG_FILE", file);
758 	r = fseek(fp, off, SEEK_CUR);
759 	if (r != 0)
760 		err(EXIT_FAILURE, "fseek() failed");
761 	for (i = 0; i < size; i++) {
762 		r = fgetc(fp);
763 		if (r == EOF)
764 			break;
765 		if (r == '\0') {
766 			assert(i == size - 1 &&
767 			    ("\\0 found in the middle of a file"));
768 			break;
769 		}
770 		fputc(r, stdout);
771 	}
772 	fclose(fp);
773 }
774 
775 static void
badversion(void)776 badversion(void)
777 {
778 	fprintf(stderr, "ERROR: version of config(8) does not match kernel!\n");
779 	fprintf(stderr, "config version = %d, ", CONFIGVERS);
780 	fprintf(stderr, "version required = %d\n\n", versreq);
781 	fprintf(stderr, "Make sure that /usr/src/usr.sbin/config is in sync\n");
782 	fprintf(stderr, "with your /usr/src/sys and install a new config binary\n");
783 	fprintf(stderr, "before trying this again.\n\n");
784 	fprintf(stderr, "If running the new config fails check your config\n");
785 	fprintf(stderr, "file against the GENERIC or LINT config files for\n");
786 	fprintf(stderr, "changes in config syntax, or option/device naming\n");
787 	fprintf(stderr, "conventions\n\n");
788 	exit(1);
789 }
790 
791 static void
checkversion(void)792 checkversion(void)
793 {
794 	FILE *ifp;
795 	char line[BUFSIZ];
796 
797 	ifp = open_makefile_template();
798 	while (fgets(line, BUFSIZ, ifp) != 0) {
799 		if (*line != '%')
800 			continue;
801 		if (strncmp(line, "%VERSREQ=", 9) != 0)
802 			continue;
803 		versreq = atoi(line + 9);
804 		if (MAJOR_VERS(versreq) == MAJOR_VERS(CONFIGVERS) &&
805 		    versreq <= CONFIGVERS)
806 			continue;
807 		badversion();
808 	}
809 	fclose(ifp);
810 }
811