xref: /linux/scripts/kconfig/streamline_config.pl (revision 46d4ccf3b621368af5e98187e9e21dccd8beb5cc)
1#!/usr/bin/env perl
2# SPDX-License-Identifier: GPL-2.0
3#
4# Copyright 2005-2009 - Steven Rostedt
5#
6#  It's simple enough to figure out how this works.
7#  If not, then you can ask me at stripconfig@goodmis.org
8#
9# What it does?
10#
11#   If you have installed a Linux kernel from a distribution
12#   that turns on way too many modules than you need, and
13#   you only want the modules you use, then this program
14#   is perfect for you.
15#
16#   It gives you the ability to turn off all the modules that are
17#   not loaded on your system.
18#
19# Howto:
20#
21#  1. Boot up the kernel that you want to stream line the config on.
22#  2. Change directory to the directory holding the source of the
23#       kernel that you just booted.
24#  3. Copy the configuration file to this directory as .config
25#  4. Have all your devices that you need modules for connected and
26#      operational (make sure that their corresponding modules are loaded)
27#  5. Run this script redirecting the output to some other file
28#       like config_strip.
29#  6. Back up your old config (if you want too).
30#  7. copy the config_strip file to .config
31#  8. Run "make oldconfig"
32#
33#  Now your kernel is ready to be built with only the modules that
34#  are loaded.
35#
36# Here's what I did with my Debian distribution.
37#
38#    cd /usr/src/linux-2.6.10
39#    cp /boot/config-2.6.10-1-686-smp .config
40#    ~/bin/streamline_config > config_strip
41#    mv .config config_sav
42#    mv config_strip .config
43#    make oldconfig
44#
45use warnings;
46use strict;
47use Getopt::Long;
48
49# set the environment variable LOCALMODCONFIG_DEBUG to get
50# debug output.
51my $debugprint = 0;
52$debugprint = 1 if (defined($ENV{LOCALMODCONFIG_DEBUG}));
53
54sub dprint {
55    return if (!$debugprint);
56    print STDERR @_;
57}
58
59my $uname = `uname -r`;
60chomp $uname;
61
62my @searchconfigs = (
63	{
64	    "file" => ".config",
65	    "exec" => "cat",
66	},
67	{
68	    "file" => "/proc/config.gz",
69	    "exec" => "zcat",
70	},
71	{
72	    "file" => "/boot/config-$uname",
73	    "exec" => "cat",
74	},
75	{
76	    "file" => "/boot/vmlinuz-$uname",
77	    "exec" => "scripts/extract-ikconfig",
78	    "test" => "scripts/extract-ikconfig",
79	},
80	{
81	    "file" => "vmlinux",
82	    "exec" => "scripts/extract-ikconfig",
83	    "test" => "scripts/extract-ikconfig",
84	},
85	{
86	    "file" => "/lib/modules/$uname/kernel/kernel/configs.ko",
87	    "exec" => "scripts/extract-ikconfig",
88	    "test" => "scripts/extract-ikconfig",
89	},
90	{
91	    "file" => "kernel/configs.ko",
92	    "exec" => "scripts/extract-ikconfig",
93	    "test" => "scripts/extract-ikconfig",
94	},
95	{
96	    "file" => "kernel/configs.o",
97	    "exec" => "scripts/extract-ikconfig",
98	    "test" => "scripts/extract-ikconfig",
99	},
100);
101
102sub read_config {
103    foreach my $conf (@searchconfigs) {
104	my $file = $conf->{"file"};
105
106	next if ( ! -f "$file");
107
108	if (defined($conf->{"test"})) {
109	    `$conf->{"test"} $conf->{"file"} 2>/dev/null`;
110	    next if ($?);
111	}
112
113	my $exec = $conf->{"exec"};
114
115	print STDERR "using config: '$file'\n";
116
117	open(my $infile, '-|', "$exec $file") || die "Failed to run $exec $file";
118	my @x = <$infile>;
119	close $infile;
120	return @x;
121    }
122    die "No config file found";
123}
124
125my @config_file = read_config;
126
127# Parse options
128my $localmodconfig = 0;
129my $localyesconfig = 0;
130
131GetOptions("localmodconfig" => \$localmodconfig,
132	   "localyesconfig" => \$localyesconfig);
133
134# Get the build source and top level Kconfig file (passed in)
135my $ksource = ($ARGV[0] ? $ARGV[0] : '.');
136my $kconfig = $ARGV[1];
137my $lsmod_file = $ENV{'LSMOD'};
138
139my @makefiles = `find $ksource -name Makefile -or -name Kbuild 2>/dev/null`;
140chomp @makefiles;
141
142my %depends;
143my %selects;
144my %prompts;
145my %objects;
146my %config2kfile;
147my %defaults;
148my %types;
149my $var;
150my $iflevel = 0;
151my @ifdeps;
152
153# prevent recursion
154my %read_kconfigs;
155
156sub read_kconfig {
157    my ($kconfig) = @_;
158
159    my $state = "NONE";
160    my $config;
161
162    my $cont = 0;
163    my $line;
164
165    my $source = "$ksource/$kconfig";
166    my $last_source = "";
167
168    # Check for any environment variables used
169    while ($source =~ /\$\((\w+)\)/ && $last_source ne $source) {
170	my $env = $1;
171	$last_source = $source;
172	$source =~ s/\$\($env\)/$ENV{$env}/;
173    }
174
175    open(my $kinfile, '<', $source) || die "Can't open $source";
176    while (<$kinfile>) {
177	chomp;
178
179	# Make sure that lines ending with \ continue
180	if ($cont) {
181	    $_ = $line . " " . $_;
182	}
183
184	if (s/\\$//) {
185	    $cont = 1;
186	    $line = $_;
187	    next;
188	}
189
190	$cont = 0;
191
192	# collect any Kconfig sources
193	if (/^source\s+"?([^"]+)/) {
194	    my $kconfig = $1;
195	    # prevent reading twice.
196	    if (!defined($read_kconfigs{$kconfig})) {
197		$read_kconfigs{$kconfig} = 1;
198		read_kconfig($kconfig);
199	    }
200	    next;
201	}
202
203	# configs found
204	if (/^\s*(menu)?config\s+(\S+)\s*$/) {
205	    $state = "NEW";
206	    $config = $2;
207	    $config2kfile{"CONFIG_$config"} = $kconfig;
208
209	    # Add depends for 'if' nesting
210	    for (my $i = 0; $i < $iflevel; $i++) {
211		if ($i) {
212		    $depends{$config} .= " " . $ifdeps[$i];
213		} else {
214		    $depends{$config} = $ifdeps[$i];
215		}
216		$state = "DEP";
217	    }
218
219	# collect the depends for the config
220	} elsif ($state eq "NEW" && /^\s*depends\s+on\s+(.*)$/) {
221	    $state = "DEP";
222	    $depends{$config} = $1;
223	} elsif ($state eq "DEP" && /^\s*depends\s+on\s+(.*)$/) {
224	    $depends{$config} .= " " . $1;
225	} elsif ($state ne "NONE" && /^\s*def(_(bool|tristate)|ault)\s+(\S.*)$/) {
226	    my $dep = $3;
227            $defaults{$config} = 1;
228	    $types{$config} = $2 if (defined($2));
229	    if ($dep !~ /^\s*(y|m|n)\s*$/) {
230		$dep =~ s/.*\sif\s+//;
231		$depends{$config} .= " " . $dep;
232		dprint "Added default depends $dep to $config\n";
233	    }
234
235	# Get the configs that select this config
236	} elsif ($state ne "NONE" && /^\s*select\s+(\S+)/) {
237	    my $conf = $1;
238	    if (defined($selects{$conf})) {
239		$selects{$conf} .= " " . $config;
240	    } else {
241		$selects{$conf} = $config;
242	    }
243
244	# configs without prompts must be selected
245	} elsif ($state ne "NONE" && /^\s*(bool|boolean)(\s+\S.*)?$/) {
246	    $types{$config} = "bool";
247	    $prompts{$config} = 1 if (defined($2));
248	} elsif ($state ne "NONE" && /^\s*tristate(\s+\S.*)?$/) {
249	    $types{$config} = "tristate";
250	    $prompts{$config} = 1 if (defined($1));
251	} elsif ($state ne "NONE" && /^\s*prompt\b/) {
252	    # note if the config has a prompt
253	    $prompts{$config} = 1;
254
255	# Check for if statements
256	} elsif (/^if\s+(.*\S)\s*$/) {
257	    my $deps = $1;
258	    # remove beginning and ending non text
259	    $deps =~ s/^[^a-zA-Z0-9_]*//;
260	    $deps =~ s/[^a-zA-Z0-9_]*$//;
261
262	    my @deps = split /[^a-zA-Z0-9_]+/, $deps;
263
264	    $ifdeps[$iflevel++] = join ':', @deps;
265
266	} elsif (/^endif/) {
267
268	    $iflevel-- if ($iflevel);
269
270	# stop on "help" and keywords that end a menu entry
271	} elsif (/^\s*(---)?help(---)?\s*$/ || /^(comment|choice|menu)\b/) {
272	    $state = "NONE";
273	}
274    }
275    close($kinfile);
276}
277
278if ($kconfig) {
279    read_kconfig($kconfig);
280}
281
282# Makefiles can use variables to define their dependencies
283sub convert_vars {
284    my ($line, %vars) = @_;
285
286    my $process = "";
287
288    while ($line =~ s/^(.*?)(\$\((.*?)\))//) {
289	my $start = $1;
290	my $variable = $2;
291	my $var = $3;
292
293	if (defined($vars{$var})) {
294	    $process .= $start . $vars{$var};
295	} else {
296	    $process .= $start . $variable;
297	}
298    }
299
300    $process .= $line;
301
302    return $process;
303}
304
305# Read all Makefiles to map the configs to the objects
306foreach my $makefile (@makefiles) {
307
308    my $line = "";
309    my %make_vars;
310
311    open(my $infile, '<', $makefile) || die "Can't open $makefile";
312    while (<$infile>) {
313	# if this line ends with a backslash, continue
314	chomp;
315	if (/^(.*)\\$/) {
316	    $line .= $1;
317	    next;
318	}
319
320	$line .= $_;
321	$_ = $line;
322	$line = "";
323
324	my $objs;
325
326	# Convert variables in a line (could define configs)
327	$_ = convert_vars($_, %make_vars);
328
329	# collect objects after obj-$(CONFIG_FOO_BAR)
330	if (/obj-\$[({](CONFIG_[^})]*)[)}]\s*[+:]?=\s*(.*)/) {
331	    $var = $1;
332	    $objs = $2;
333
334	# check if variables are set
335	} elsif (/^\s*(\S+)\s*[:]?=\s*(.*\S)/) {
336	    $make_vars{$1} = $2;
337	}
338	if (defined($objs)) {
339	    foreach my $obj (split /\s+/,$objs) {
340		$obj =~ s/-/_/g;
341		if ($obj =~ /(.*)\.o$/) {
342		    # Objects may be enabled by more than one config.
343		    # Store configs in an array.
344		    my @arr;
345
346		    if (defined($objects{$1})) {
347			@arr = @{$objects{$1}};
348		    }
349
350		    $arr[$#arr+1] = $var;
351
352		    # The objects have a hash mapping to a reference
353		    # of an array of configs.
354		    $objects{$1} = \@arr;
355		}
356	    }
357	}
358    }
359    close($infile);
360}
361
362my %modules;
363my $linfile;
364
365if (defined($lsmod_file)) {
366    if ( ! -f $lsmod_file) {
367	if ( -f $ENV{'objtree'}."/".$lsmod_file) {
368	    $lsmod_file = $ENV{'objtree'}."/".$lsmod_file;
369	} else {
370		die "$lsmod_file not found";
371	}
372    }
373
374    my $otype = ( -x $lsmod_file) ? '-|' : '<';
375    open($linfile, $otype, $lsmod_file);
376
377} else {
378
379    # see what modules are loaded on this system
380    my $lsmod;
381
382    foreach my $dir ( ("/sbin", "/bin", "/usr/sbin", "/usr/bin") ) {
383	if ( -x "$dir/lsmod" ) {
384	    $lsmod = "$dir/lsmod";
385	    last;
386	}
387    }
388    if (!defined($lsmod)) {
389	# try just the path
390	$lsmod = "lsmod";
391    }
392
393    open($linfile, '-|', $lsmod) || die "Can not call lsmod with $lsmod";
394}
395
396while (<$linfile>) {
397	next if (/^Module/);  # Skip the first line.
398	if (/^(\S+)/) {
399		$modules{$1} = 1;
400	}
401}
402close ($linfile);
403
404# add to the configs hash all configs that are needed to enable
405# a loaded module. This is a direct obj-${CONFIG_FOO} += bar.o
406# where we know we need bar.o so we add FOO to the list.
407my %configs;
408foreach my $module (keys(%modules)) {
409    if (defined($objects{$module})) {
410	my @arr = @{$objects{$module}};
411	foreach my $conf (@arr) {
412	    $configs{$conf} = $module;
413	    dprint "$conf added by direct ($module)\n";
414	    if ($debugprint) {
415		my $c=$conf;
416		$c =~ s/^CONFIG_//;
417		if (defined($depends{$c})) {
418		    dprint " deps = $depends{$c}\n";
419		} else {
420		    dprint " no deps\n";
421		}
422	    }
423	}
424    } else {
425	# Most likely, someone has a custom (binary?) module loaded.
426	print STDERR "$module config not found!\n";
427    }
428}
429
430# Read the current config, and see what is enabled. We want to
431# ignore configs that we would not enable anyway.
432
433my %orig_configs;
434my $valid = "A-Za-z_0-9";
435
436foreach my $line (@config_file) {
437    $_ = $line;
438
439    if (/(CONFIG_[$valid]*)=(m|y)/) {
440	$orig_configs{$1} = $2;
441    }
442}
443
444my $repeat = 1;
445
446my $depconfig;
447
448#
449# Note, we do not care about operands (like: &&, ||, !) we want to add any
450# config that is in the depend list of another config. This script does
451# not enable configs that are not already enabled. If we come across a
452# config A that depends on !B, we can still add B to the list of depends
453# to keep on. If A was on in the original config, B would not have been
454# and B would not be turned on by this script.
455#
456sub parse_config_depends
457{
458    my ($p) = @_;
459
460    while ($p =~ /[$valid]/) {
461
462	if ($p =~ /^[^$valid]*([$valid]+)/) {
463	    my $conf = "CONFIG_" . $1;
464
465	    $p =~ s/^[^$valid]*[$valid]+//;
466
467	    # We only need to process if the depend config is a module
468	    if (!defined($orig_configs{$conf}) || $orig_configs{$conf} eq "y") {
469		next;
470	    }
471
472	    if (!defined($configs{$conf})) {
473		# We must make sure that this config has its
474		# dependencies met.
475		$repeat = 1; # do again
476		dprint "$conf selected by depend $depconfig\n";
477		$configs{$conf} = 1;
478	    }
479	} else {
480	    die "this should never happen";
481	}
482    }
483}
484
485# Select is treated a bit differently than depends. We call this
486# when a config has no prompt and requires another config to be
487# selected. We use to just select all configs that selected this
488# config, but found that that can balloon into enabling hundreds
489# of configs that we do not care about.
490#
491# The idea is we look at all the configs that select it. If one
492# is already in our list of configs to enable, then there's nothing
493# else to do. If there isn't, we pick the first config that was
494# enabled in the original config and use that.
495sub parse_config_selects
496{
497    my ($config, $p) = @_;
498
499    my $next_config;
500
501    while ($p =~ /[$valid]/) {
502
503	if ($p =~ /^[^$valid]*([$valid]+)/) {
504	    my $conf = "CONFIG_" . $1;
505
506	    $p =~ s/^[^$valid]*[$valid]+//;
507
508	    # Make sure that this config exists in the current .config file
509	    if (!defined($orig_configs{$conf})) {
510		dprint "$conf not set for $config select\n";
511		next;
512	    }
513
514	    # Check if something other than a module selects this config
515	    if (defined($orig_configs{$conf}) && $orig_configs{$conf} ne "m") {
516		dprint "$conf (non module) selects $config, we are good\n";
517		# we are good with this
518		return;
519	    }
520	    if (defined($configs{$conf})) {
521		dprint "$conf selects $config so we are good\n";
522		# A set config selects this config, we are good
523		return;
524	    }
525	    # Set this config to be selected
526	    if (!defined($next_config)) {
527		$next_config = $conf;
528	    }
529	} else {
530	    die "this should never happen";
531	}
532    }
533
534    # If no possible config selected this, then something happened.
535    if (!defined($next_config)) {
536
537	# Some config options have no prompt, and nothing selects them, but
538	# they stay turned on once the final checks for the configs
539	# are done. These configs have a default option, so turn off the
540	# warnings for configs with default options.
541	if (!defined($defaults{$config})) {
542	    print STDERR "WARNING: $config is required, but nothing in the\n";
543	    print STDERR "  current config selects it.\n";
544	}
545
546	return;
547    }
548
549    # If we are here, then we found no config that is set and
550    # selects this config. Repeat.
551    $repeat = 1;
552    # Make this config need to be selected
553    $configs{$next_config} = 1;
554    dprint "$next_config selected by select $config\n";
555}
556
557my %process_selects;
558
559# loop through all configs, select their dependencies.
560sub loop_depend {
561    $repeat = 1;
562
563    while ($repeat) {
564	$repeat = 0;
565
566      forloop:
567	foreach my $config (keys %configs) {
568
569	    # If this config is not a module, we do not need to process it
570	    if (defined($orig_configs{$config}) && $orig_configs{$config} ne "m") {
571		next forloop;
572	    }
573
574	    $config =~ s/^CONFIG_//;
575	    $depconfig = $config;
576
577	    if (defined($depends{$config})) {
578		# This config has dependencies. Make sure they are also included
579		parse_config_depends $depends{$config};
580	    }
581
582	    # If the config has no prompt, then we need to check if a config
583	    # that is enabled selected it. Or if we need to enable one.
584	    if (!defined($prompts{$config}) && defined($selects{$config})) {
585		$process_selects{$config} = 1;
586	    }
587	}
588    }
589}
590
591sub loop_select {
592
593    foreach my $config (keys %process_selects) {
594	$config =~ s/^CONFIG_//;
595
596	dprint "Process select $config\n";
597
598	# config has no prompt and must be selected.
599	parse_config_selects $config, $selects{$config};
600    }
601}
602
603while ($repeat) {
604    # Get the first set of configs and their dependencies.
605    loop_depend;
606
607    $repeat = 0;
608
609    # Now we need to see if we have to check selects;
610    loop_select;
611}
612
613my %setconfigs;
614my @preserved_kconfigs;
615if (defined($ENV{'LMC_KEEP'})) {
616	@preserved_kconfigs = split(/:/,$ENV{LMC_KEEP});
617}
618
619sub in_preserved_kconfigs {
620    my $kconfig = $config2kfile{$_[0]};
621    if (!defined($kconfig)) {
622	return 0;
623    }
624    foreach my $excl (@preserved_kconfigs) {
625	if($kconfig =~ /^$excl/) {
626	    return 1;
627	}
628    }
629    return 0;
630}
631
632# Finally, read the .config file and turn off any module enabled that
633# we could not find a reason to keep enabled.
634foreach my $line (@config_file) {
635    $_ = $line;
636
637    if (/CONFIG_IKCONFIG/) {
638	if (/# CONFIG_IKCONFIG is not set/) {
639	    # enable IKCONFIG at least as a module
640	    print "CONFIG_IKCONFIG=m\n";
641	    # don't ask about PROC
642	    print "# CONFIG_IKCONFIG_PROC is not set\n";
643	} else {
644	    print;
645	}
646	next;
647    }
648
649    if (/CONFIG_MODULE_SIG_KEY="(.+)"/) {
650	my $orig_cert = $1;
651	my $default_cert = "certs/signing_key.pem";
652
653	# Check that the logic in this script still matches the one in Kconfig
654	if (!defined($depends{"MODULE_SIG_KEY"}) ||
655	    $depends{"MODULE_SIG_KEY"} !~ /"\Q$default_cert\E"/) {
656	    print STDERR "WARNING: MODULE_SIG_KEY assertion failure, ",
657		"update needed to ", __FILE__, " line ", __LINE__, "\n";
658	    print;
659	} elsif ($orig_cert ne $default_cert && ! -f $orig_cert) {
660	    print STDERR "Module signature verification enabled but ",
661		"module signing key \"$orig_cert\" not found. Resetting ",
662		"signing key to default value.\n";
663	    print "CONFIG_MODULE_SIG_KEY=\"$default_cert\"\n";
664	} else {
665	    print;
666	}
667	next;
668    }
669
670    if (/CONFIG_SYSTEM_TRUSTED_KEYS="(.+)"/) {
671	my $orig_keys = $1;
672
673	if (! -f $orig_keys) {
674	    print STDERR "System keyring enabled but keys \"$orig_keys\" ",
675		"not found. Resetting keys to default value.\n";
676	    print "CONFIG_SYSTEM_TRUSTED_KEYS=\"\"\n";
677	} else {
678	    print;
679	}
680	next;
681    }
682
683    if (/^(CONFIG.*)=(m|y)/) {
684	if (in_preserved_kconfigs($1)) {
685	    dprint "Preserve config $1";
686	    print;
687	    next;
688	}
689	if (defined($configs{$1})) {
690	    if ($localyesconfig) {
691		$setconfigs{$1} = 'y';
692		print "$1=y\n";
693		next;
694	    } else {
695		$setconfigs{$1} = $2;
696	    }
697	} elsif ($2 eq "m") {
698	    print "# $1 is not set\n";
699	    next;
700	}
701    }
702    print;
703}
704
705# Integrity check, make sure all modules that we want enabled do
706# indeed have their configs set.
707loop:
708foreach my $module (keys(%modules)) {
709    if (defined($objects{$module})) {
710	my @arr = @{$objects{$module}};
711	foreach my $conf (@arr) {
712	    if (defined($setconfigs{$conf})) {
713		next loop;
714	    }
715	}
716	print STDERR "module $module did not have configs";
717	foreach my $conf (@arr) {
718	    my $c = $conf;
719	    $c =~ s/^CONFIG_//;
720	    if (!$localyesconfig && defined($types{$c}) && $types{$c} eq "bool") {
721		print STDERR " $conf (boolean, not supported with =m)";
722	    } elsif (defined($types{$c})) {
723		print STDERR " $conf ($types{$c})";
724	    } else {
725		print STDERR " " , $conf;
726	    }
727	}
728	print STDERR "\n";
729    }
730}
731
732# vim: softtabstop=4
733