5 # SPDX-License-Identifier: GPL-2.0+
9 Move config options from headers to defconfig files.
11 Since Kconfig was introduced to U-Boot, we have worked on moving
12 config options from headers to Kconfig (defconfig).
14 This tool intends to help this tremendous work.
20 First, you must edit the Kconfig to add the menu entries for the configs
23 And then run this tool giving CONFIG names you want to move.
24 For example, if you want to move CONFIG_CMD_USB and CONFIG_SYS_TEXT_BASE,
25 simply type as follows:
27 $ tools/moveconfig.py CONFIG_CMD_USB CONFIG_SYS_TEXT_BASE
29 The tool walks through all the defconfig files and move the given CONFIGs.
31 The log is also displayed on the terminal.
33 The log is printed for each defconfig as follows:
41 <defconfig_name> is the name of the defconfig.
43 <action*> shows what the tool did for that defconfig.
44 It looks like one of the following:
47 This config option was moved to the defconfig
49 - CONFIG_... is not defined in Kconfig. Do nothing.
50 The entry for this CONFIG was not found in Kconfig. The option is not
51 defined in the config header, either. So, this case can be just skipped.
53 - CONFIG_... is not defined in Kconfig (suspicious). Do nothing.
54 This option is defined in the config header, but its entry was not found
56 There are two common cases:
57 - You forgot to create an entry for the CONFIG before running
58 this tool, or made a typo in a CONFIG passed to this tool.
59 - The entry was hidden due to unmet 'depends on'.
60 The tool does not know if the result is reasonable, so please check it
63 - 'CONFIG_...' is the same as the define in Kconfig. Do nothing.
64 The define in the config header matched the one in Kconfig.
65 We do not need to touch it.
67 - Compiler is missing. Do nothing.
68 The compiler specified for this architecture was not found
69 in your PATH environment.
70 (If -e option is passed, the tool exits immediately.)
73 An error occurred during processing this defconfig. Skipped.
74 (If -e option is passed, the tool exits immediately on error.)
76 Finally, you will be asked, Clean up headers? [y/n]:
78 If you say 'y' here, the unnecessary config defines are removed
79 from the config headers (include/configs/*.h).
80 It just uses the regex method, so you should not rely on it.
81 Just in case, please do 'git diff' to see what happened.
87 This tool runs configuration and builds include/autoconf.mk for every
88 defconfig. The config options defined in Kconfig appear in the .config
89 file (unless they are hidden because of unmet dependency.)
90 On the other hand, the config options defined by board headers are seen
91 in include/autoconf.mk. The tool looks for the specified options in both
92 of them to decide the appropriate action for the options. If the given
93 config option is found in the .config, but its value does not match the
94 one from the board header, the config option in the .config is replaced
95 with the define in the board header. Then, the .config is synced by
96 "make savedefconfig" and the defconfig is updated with it.
98 For faster processing, this tool handles multi-threading. It creates
99 separate build directories where the out-of-tree build is run. The
100 temporary build directories are automatically created and deleted as
101 needed. The number of threads are chosen based on the number of the CPU
102 cores of your system although you can change it via -j (--jobs) option.
108 Appropriate toolchain are necessary to generate include/autoconf.mk
109 for all the architectures supported by U-Boot. Most of them are available
110 at the kernel.org site, some are not provided by kernel.org.
112 The default per-arch CROSS_COMPILE used by this tool is specified by
113 the list below, CROSS_COMPILE. You may wish to update the list to
114 use your own. Instead of modifying the list directly, you can give
115 them via environments.
121 To sync only X86 defconfigs:
123 ./tools/moveconfig.py -s -d <(grep -l X86 configs/*)
127 grep -l X86 configs/* | ./tools/moveconfig.py -s -d -
129 To process CONFIG_CMD_FPGAD only for a subset of configs based on path match:
131 ls configs/{hrcon*,iocon*,strider*} | \
132 ./tools/moveconfig.py -Cy CONFIG_CMD_FPGAD -d -
135 Finding implied CONFIGs
136 -----------------------
138 Some CONFIG options can be implied by others and this can help to reduce
139 the size of the defconfig files. For example, CONFIG_X86 implies
140 CONFIG_CMD_IRQ, so we can put 'imply CMD_IRQ' under 'config X86' and
141 all x86 boards will have that option, avoiding adding CONFIG_CMD_IRQ to
142 each of the x86 defconfig files.
144 This tool can help find such configs. To use it, first build a database:
146 ./tools/moveconfig.py -b
148 Then try to query it:
150 ./tools/moveconfig.py -i CONFIG_CMD_IRQ
151 CONFIG_CMD_IRQ found in 311/2384 defconfigs
152 44 : CONFIG_SYS_FSL_ERRATUM_IFC_A002769
153 41 : CONFIG_SYS_FSL_ERRATUM_A007075
154 31 : CONFIG_SYS_FSL_DDR_VER_44
155 28 : CONFIG_ARCH_P1010
156 28 : CONFIG_SYS_FSL_ERRATUM_P1010_A003549
157 28 : CONFIG_SYS_FSL_ERRATUM_SEC_A003571
158 28 : CONFIG_SYS_FSL_ERRATUM_IFC_A003399
159 25 : CONFIG_SYS_FSL_ERRATUM_A008044
160 22 : CONFIG_ARCH_P1020
161 21 : CONFIG_SYS_FSL_DDR_VER_46
162 20 : CONFIG_MAX_PIRQ_LINKS
163 20 : CONFIG_HPET_ADDRESS
165 20 : CONFIG_PCIE_ECAM_SIZE
166 20 : CONFIG_IRQ_SLOT_COUNT
167 20 : CONFIG_I8259_PIC
168 20 : CONFIG_CPU_ADDR_BITS
170 20 : CONFIG_SYS_FSL_ERRATUM_A005871
171 20 : CONFIG_PCIE_ECAM_BASE
172 20 : CONFIG_X86_TSC_TIMER
173 20 : CONFIG_I8254_TIMER
174 20 : CONFIG_CMD_GETTIME
175 19 : CONFIG_SYS_FSL_ERRATUM_A005812
176 18 : CONFIG_X86_RUN_32BIT
177 17 : CONFIG_CMD_CHIP_CONFIG
180 This shows a list of config options which might imply CONFIG_CMD_EEPROM along
181 with how many defconfigs they cover. From this you can see that CONFIG_X86
182 implies CONFIG_CMD_EEPROM. Therefore, instead of adding CONFIG_CMD_EEPROM to
183 the defconfig of every x86 board, you could add a single imply line to the
187 bool "x86 architecture"
191 That will cover 20 defconfigs. Many of the options listed are not suitable as
192 they are not related. E.g. it would be odd for CONFIG_CMD_GETTIME to imply
195 Using this search you can reduce the size of moveconfig patches.
197 You can automatically add 'imply' statements in the Kconfig with the -a
200 ./tools/moveconfig.py -s -i CONFIG_SCSI \
201 -a CONFIG_ARCH_LS1021A,CONFIG_ARCH_LS1043A
203 This will add 'imply SCSI' to the two CONFIG options mentioned, assuming that
204 the database indicates that they do actually imply CONFIG_SCSI and do not
205 already have an 'imply SCSI'.
207 The output shows where the imply is added:
209 18 : CONFIG_ARCH_LS1021A arch/arm/cpu/armv7/ls102xa/Kconfig:1
210 13 : CONFIG_ARCH_LS1043A arch/arm/cpu/armv8/fsl-layerscape/Kconfig:11
211 12 : CONFIG_ARCH_LS1046A arch/arm/cpu/armv8/fsl-layerscape/Kconfig:31
213 The first number is the number of boards which can avoid having a special
214 CONFIG_SCSI option in their defconfig file if this 'imply' is added.
215 The location at the right is the Kconfig file and line number where the config
216 appears. For example, adding 'imply CONFIG_SCSI' to the 'config ARCH_LS1021A'
217 in arch/arm/cpu/armv7/ls102xa/Kconfig at line 1 will help 18 boards to reduce
218 the size of their defconfig files.
220 If you want to add an 'imply' to every imply config in the list, you can use
222 ./tools/moveconfig.py -s -i CONFIG_SCSI -a all
224 To control which ones are displayed, use -I <list> where list is a list of
225 options (use '-I help' to see possible options and their meaning).
227 To skip showing you options that already have an 'imply' attached, use -A.
229 When you have finished adding 'imply' options you can regenerate the
230 defconfig files for affected boards with something like:
232 git show --stat | ./tools/moveconfig.py -s -d -
234 This will regenerate only those defconfigs changed in the current commit.
235 If you start with (say) 100 defconfigs being changed in the commit, and add
236 a few 'imply' options as above, then regenerate, hopefully you can reduce the
237 number of defconfigs changed in the commit.
244 Surround each portion of the log with escape sequences to display it
245 in color on the terminal.
248 Create a git commit with the changes when the operation is complete. A
249 standard commit message is used which may need to be edited.
252 Specify a file containing a list of defconfigs to move. The defconfig
253 files can be given with shell-style wildcards. Use '-' to read from stdin.
256 Perform a trial run that does not make any changes. It is useful to
257 see what is going to happen before one actually runs it.
260 Exit immediately if Make exits with a non-zero status while processing
264 Do "make savedefconfig" forcibly for all the defconfig files.
265 If not specified, "make savedefconfig" only occurs for cases
266 where at least one CONFIG was moved.
269 Look for moved config options in spl/include/autoconf.mk instead of
270 include/autoconf.mk. This is useful for moving options for SPL build
271 because SPL related options (mostly prefixed with CONFIG_SPL_) are
272 sometimes blocked by CONFIG_SPL_BUILD ifdef conditionals.
275 Only cleanup the headers; skip the defconfig processing
278 Specify the number of threads to run simultaneously. If not specified,
279 the number of threads is the same as the number of CPU cores.
282 Specify the git ref to clone for building the autoconf.mk. If unspecified
283 use the CWD. This is useful for when changes to the Kconfig affect the
284 default values and you want to capture the state of the defconfig from
285 before that change was in effect. If in doubt, specify a ref pre-Kconfig
286 changes (use HEAD if Kconfig changes are not committed). Worst case it will
287 take a bit longer to run, but will always do the right thing.
290 Show any build errors as boards are built
293 Instead of prompting, automatically go ahead with all operations. This
294 includes cleaning up headers, CONFIG_SYS_EXTRA_OPTIONS, the config whitelist
297 To see the complete list of supported options, run
299 $ tools/moveconfig.py -h
309 import multiprocessing
321 sys.path.append(os.path.join(os.path.dirname(__file__), 'buildman'))
324 SHOW_GNU_MAKE = 'scripts/show-gnu-make'
327 # Here is the list of cross-tools I use.
328 # Most of them are available at kernel.org
329 # (https://www.kernel.org/pub/tools/crosstool/files/bin/), except the following:
330 # arc: https://github.com/foss-for-synopsys-dwc-arc-processors/toolchain/releases
331 # nds32: http://osdk.andestech.com/packages/nds32le-linux-glibc-v1.tgz
332 # nios2: https://sourcery.mentor.com/GNUToolchain/subscription42545
333 # sh: http://sourcery.mentor.com/public/gnu_toolchain/sh-linux-gnu
336 'aarch64': 'aarch64-linux-',
337 'arm': 'arm-unknown-linux-gnueabi-',
338 'm68k': 'm68k-linux-',
339 'microblaze': 'microblaze-linux-',
340 'mips': 'mips-linux-',
341 'nds32': 'nds32le-linux-',
342 'nios2': 'nios2-linux-gnu-',
343 'powerpc': 'powerpc-linux-',
344 'sh': 'sh-linux-gnu-',
345 'x86': 'i386-linux-',
346 'xtensa': 'xtensa-linux-'
352 STATE_SAVEDEFCONFIG = 3
356 ACTION_NO_ENTRY_WARN = 2
364 COLOR_PURPLE = '0;35'
366 COLOR_LIGHT_GRAY = '0;37'
367 COLOR_DARK_GRAY = '1;30'
368 COLOR_LIGHT_RED = '1;31'
369 COLOR_LIGHT_GREEN = '1;32'
370 COLOR_YELLOW = '1;33'
371 COLOR_LIGHT_BLUE = '1;34'
372 COLOR_LIGHT_PURPLE = '1;35'
373 COLOR_LIGHT_CYAN = '1;36'
376 AUTO_CONF_PATH = 'include/config/auto.conf'
377 CONFIG_DATABASE = 'moveconfig.db'
379 CONFIG_LEN = len('CONFIG_')
381 ### helper functions ###
383 """Get the file object of '/dev/null' device."""
385 devnull = subprocess.DEVNULL # py3k
386 except AttributeError:
387 devnull = open(os.devnull, 'wb')
390 def check_top_directory():
391 """Exit if we are not at the top of source directory."""
392 for f in ('README', 'Licenses'):
393 if not os.path.exists(f):
394 sys.exit('Please run at the top of source directory.')
396 def check_clean_directory():
397 """Exit if the source tree is not clean."""
398 for f in ('.config', 'include/config'):
399 if os.path.exists(f):
400 sys.exit("source tree is not clean, please run 'make mrproper'")
403 """Get the command name of GNU Make.
405 U-Boot needs GNU Make for building, but the command name is not
406 necessarily "make". (for example, "gmake" on FreeBSD).
407 Returns the most appropriate command name on your system.
409 process = subprocess.Popen([SHOW_GNU_MAKE], stdout=subprocess.PIPE)
410 ret = process.communicate()
411 if process.returncode:
412 sys.exit('GNU Make not found')
413 return ret[0].rstrip()
415 def get_matched_defconfig(line):
416 """Get the defconfig files that match a pattern
419 line: Path or filename to match, e.g. 'configs/snow_defconfig' or
420 'k2*_defconfig'. If no directory is provided, 'configs/' is
424 a list of matching defconfig files
426 dirname = os.path.dirname(line)
430 pattern = os.path.join('configs', line)
431 return glob.glob(pattern) + glob.glob(pattern + '_defconfig')
433 def get_matched_defconfigs(defconfigs_file):
434 """Get all the defconfig files that match the patterns in a file.
437 defconfigs_file: File containing a list of defconfigs to process, or
438 '-' to read the list from stdin
441 A list of paths to defconfig files, with no duplicates
444 if defconfigs_file == '-':
446 defconfigs_file = 'stdin'
448 fd = open(defconfigs_file)
449 for i, line in enumerate(fd):
452 continue # skip blank lines silently
454 line = line.split(' ')[0] # handle 'git log' input
455 matched = get_matched_defconfig(line)
457 print >> sys.stderr, "warning: %s:%d: no defconfig matched '%s'" % \
458 (defconfigs_file, i + 1, line)
460 defconfigs += matched
462 # use set() to drop multiple matching
463 return [ defconfig[len('configs') + 1:] for defconfig in set(defconfigs) ]
465 def get_all_defconfigs():
466 """Get all the defconfig files under the configs/ directory."""
468 for (dirpath, dirnames, filenames) in os.walk('configs'):
469 dirpath = dirpath[len('configs') + 1:]
470 for filename in fnmatch.filter(filenames, '*_defconfig'):
471 defconfigs.append(os.path.join(dirpath, filename))
475 def color_text(color_enabled, color, string):
476 """Return colored string."""
478 # LF should not be surrounded by the escape sequence.
479 # Otherwise, additional whitespace or line-feed might be printed.
480 return '\n'.join([ '\033[' + color + 'm' + s + '\033[0m' if s else ''
481 for s in string.split('\n') ])
485 def show_diff(a, b, file_path, color_enabled):
486 """Show unidified diff.
489 a: A list of lines (before)
490 b: A list of lines (after)
491 file_path: Path to the file
492 color_enabled: Display the diff in color
495 diff = difflib.unified_diff(a, b,
496 fromfile=os.path.join('a', file_path),
497 tofile=os.path.join('b', file_path))
500 if line[0] == '-' and line[1] != '-':
501 print color_text(color_enabled, COLOR_RED, line),
502 elif line[0] == '+' and line[1] != '+':
503 print color_text(color_enabled, COLOR_GREEN, line),
507 def update_cross_compile(color_enabled):
508 """Update per-arch CROSS_COMPILE via environment variables
510 The default CROSS_COMPILE values are available
511 in the CROSS_COMPILE list above.
513 You can override them via environment variables
514 CROSS_COMPILE_{ARCH}.
516 For example, if you want to override toolchain prefixes
517 for ARM and PowerPC, you can do as follows in your shell:
519 export CROSS_COMPILE_ARM=...
520 export CROSS_COMPILE_POWERPC=...
522 Then, this function checks if specified compilers really exist in your
527 for arch in os.listdir('arch'):
528 if os.path.exists(os.path.join('arch', arch, 'Makefile')):
531 # arm64 is a special case
532 archs.append('aarch64')
535 env = 'CROSS_COMPILE_' + arch.upper()
536 cross_compile = os.environ.get(env)
537 if not cross_compile:
538 cross_compile = CROSS_COMPILE.get(arch, '')
540 for path in os.environ["PATH"].split(os.pathsep):
541 gcc_path = os.path.join(path, cross_compile + 'gcc')
542 if os.path.isfile(gcc_path) and os.access(gcc_path, os.X_OK):
545 print >> sys.stderr, color_text(color_enabled, COLOR_YELLOW,
546 'warning: %sgcc: not found in PATH. %s architecture boards will be skipped'
547 % (cross_compile, arch))
550 CROSS_COMPILE[arch] = cross_compile
552 def extend_matched_lines(lines, matched, pre_patterns, post_patterns, extend_pre,
554 """Extend matched lines if desired patterns are found before/after already
558 lines: A list of lines handled.
559 matched: A list of line numbers that have been already matched.
560 (will be updated by this function)
561 pre_patterns: A list of regular expression that should be matched as
563 post_patterns: A list of regular expression that should be matched as
565 extend_pre: Add the line number of matched preamble to the matched list.
566 extend_post: Add the line number of matched postamble to the matched list.
568 extended_matched = []
581 for p in pre_patterns:
582 if p.search(lines[i - 1]):
588 for p in post_patterns:
589 if p.search(lines[j]):
596 extended_matched.append(i - 1)
598 extended_matched.append(j)
600 matched += extended_matched
603 def confirm(options, prompt):
606 choice = raw_input('{} [y/n]: '.format(prompt))
607 choice = choice.lower()
609 if choice == 'y' or choice == 'n':
617 def cleanup_one_header(header_path, patterns, options):
618 """Clean regex-matched lines away from a file.
621 header_path: path to the cleaned file.
622 patterns: list of regex patterns. Any lines matching to these
623 patterns are deleted.
624 options: option flags.
626 with open(header_path) as f:
627 lines = f.readlines()
630 for i, line in enumerate(lines):
631 if i - 1 in matched and lines[i - 1][-2:] == '\\\n':
634 for pattern in patterns:
635 if pattern.search(line):
642 # remove empty #ifdef ... #endif, successive blank lines
643 pattern_if = re.compile(r'#\s*if(def|ndef)?\W') # #if, #ifdef, #ifndef
644 pattern_elif = re.compile(r'#\s*el(if|se)\W') # #elif, #else
645 pattern_endif = re.compile(r'#\s*endif\W') # #endif
646 pattern_blank = re.compile(r'^\s*$') # empty line
649 old_matched = copy.copy(matched)
650 extend_matched_lines(lines, matched, [pattern_if],
651 [pattern_endif], True, True)
652 extend_matched_lines(lines, matched, [pattern_elif],
653 [pattern_elif, pattern_endif], True, False)
654 extend_matched_lines(lines, matched, [pattern_if, pattern_elif],
655 [pattern_blank], False, True)
656 extend_matched_lines(lines, matched, [pattern_blank],
657 [pattern_elif, pattern_endif], True, False)
658 extend_matched_lines(lines, matched, [pattern_blank],
659 [pattern_blank], True, False)
660 if matched == old_matched:
663 tolines = copy.copy(lines)
665 for i in reversed(matched):
668 show_diff(lines, tolines, header_path, options.color)
673 with open(header_path, 'w') as f:
677 def cleanup_headers(configs, options):
678 """Delete config defines from board headers.
681 configs: A list of CONFIGs to remove.
682 options: option flags.
684 if not confirm(options, 'Clean up headers?'):
688 for config in configs:
689 patterns.append(re.compile(r'#\s*define\s+%s\W' % config))
690 patterns.append(re.compile(r'#\s*undef\s+%s\W' % config))
692 for dir in 'include', 'arch', 'board':
693 for (dirpath, dirnames, filenames) in os.walk(dir):
694 if dirpath == os.path.join('include', 'generated'):
696 for filename in filenames:
697 if not fnmatch.fnmatch(filename, '*~'):
698 cleanup_one_header(os.path.join(dirpath, filename),
701 def cleanup_one_extra_option(defconfig_path, configs, options):
702 """Delete config defines in CONFIG_SYS_EXTRA_OPTIONS in one defconfig file.
705 defconfig_path: path to the cleaned defconfig file.
706 configs: A list of CONFIGs to remove.
707 options: option flags.
710 start = 'CONFIG_SYS_EXTRA_OPTIONS="'
713 with open(defconfig_path) as f:
714 lines = f.readlines()
716 for i, line in enumerate(lines):
717 if line.startswith(start) and line.endswith(end):
720 # CONFIG_SYS_EXTRA_OPTIONS was not found in this defconfig
723 old_tokens = line[len(start):-len(end)].split(',')
726 for token in old_tokens:
727 pos = token.find('=')
728 if not (token[:pos] if pos >= 0 else token) in configs:
729 new_tokens.append(token)
731 if new_tokens == old_tokens:
734 tolines = copy.copy(lines)
737 tolines[i] = start + ','.join(new_tokens) + end
741 show_diff(lines, tolines, defconfig_path, options.color)
746 with open(defconfig_path, 'w') as f:
750 def cleanup_extra_options(configs, options):
751 """Delete config defines in CONFIG_SYS_EXTRA_OPTIONS in defconfig files.
754 configs: A list of CONFIGs to remove.
755 options: option flags.
757 if not confirm(options, 'Clean up CONFIG_SYS_EXTRA_OPTIONS?'):
760 configs = [ config[len('CONFIG_'):] for config in configs ]
762 defconfigs = get_all_defconfigs()
764 for defconfig in defconfigs:
765 cleanup_one_extra_option(os.path.join('configs', defconfig), configs,
768 def cleanup_whitelist(configs, options):
769 """Delete config whitelist entries
772 configs: A list of CONFIGs to remove.
773 options: option flags.
775 if not confirm(options, 'Clean up whitelist entries?'):
778 with open(os.path.join('scripts', 'config_whitelist.txt')) as f:
779 lines = f.readlines()
781 lines = [x for x in lines if x.strip() not in configs]
783 with open(os.path.join('scripts', 'config_whitelist.txt'), 'w') as f:
784 f.write(''.join(lines))
786 def find_matching(patterns, line):
792 def cleanup_readme(configs, options):
793 """Delete config description in README
796 configs: A list of CONFIGs to remove.
797 options: option flags.
799 if not confirm(options, 'Clean up README?'):
803 for config in configs:
804 patterns.append(re.compile(r'^\s+%s' % config))
806 with open('README') as f:
807 lines = f.readlines()
813 found = find_matching(patterns, line)
817 if found and re.search(r'^\s+CONFIG', line):
821 newlines.append(line)
823 with open('README', 'w') as f:
824 f.write(''.join(newlines))
830 """Progress Indicator"""
832 def __init__(self, total):
833 """Create a new progress indicator.
836 total: A number of defconfig files to process.
842 """Increment the number of processed defconfig files."""
847 """Display the progress."""
848 print ' %d defconfigs out of %d\r' % (self.current, self.total),
852 class KconfigScanner:
853 """Kconfig scanner."""
856 """Scan all the Kconfig files and create a Config object."""
857 # Define environment variables referenced from Kconfig
858 os.environ['srctree'] = os.getcwd()
859 os.environ['UBOOTVERSION'] = 'dummy'
860 os.environ['KCONFIG_OBJDIR'] = ''
861 self.conf = kconfiglib.Config()
866 """A parser of .config and include/autoconf.mk."""
868 re_arch = re.compile(r'CONFIG_SYS_ARCH="(.*)"')
869 re_cpu = re.compile(r'CONFIG_SYS_CPU="(.*)"')
871 def __init__(self, configs, options, build_dir):
872 """Create a new parser.
875 configs: A list of CONFIGs to move.
876 options: option flags.
877 build_dir: Build directory.
879 self.configs = configs
880 self.options = options
881 self.dotconfig = os.path.join(build_dir, '.config')
882 self.autoconf = os.path.join(build_dir, 'include', 'autoconf.mk')
883 self.spl_autoconf = os.path.join(build_dir, 'spl', 'include',
885 self.config_autoconf = os.path.join(build_dir, AUTO_CONF_PATH)
886 self.defconfig = os.path.join(build_dir, 'defconfig')
888 def get_cross_compile(self):
889 """Parse .config file and return CROSS_COMPILE.
892 A string storing the compiler prefix for the architecture.
893 Return a NULL string for architectures that do not require
894 compiler prefix (Sandbox and native build is the case).
895 Return None if the specified compiler is missing in your PATH.
896 Caller should distinguish '' and None.
900 for line in open(self.dotconfig):
901 m = self.re_arch.match(line)
905 m = self.re_cpu.match(line)
913 if arch == 'arm' and cpu == 'armv8':
916 return CROSS_COMPILE.get(arch, None)
918 def parse_one_config(self, config, dotconfig_lines, autoconf_lines):
919 """Parse .config, defconfig, include/autoconf.mk for one config.
921 This function looks for the config options in the lines from
922 defconfig, .config, and include/autoconf.mk in order to decide
923 which action should be taken for this defconfig.
926 config: CONFIG name to parse.
927 dotconfig_lines: lines from the .config file.
928 autoconf_lines: lines from the include/autoconf.mk file.
931 A tupple of the action for this defconfig and the line
932 matched for the config.
934 not_set = '# %s is not set' % config
936 for line in autoconf_lines:
938 if line.startswith(config + '='):
944 for line in dotconfig_lines:
946 if line.startswith(config + '=') or line == not_set:
950 if new_val == not_set:
951 return (ACTION_NO_ENTRY, config)
953 return (ACTION_NO_ENTRY_WARN, config)
955 # If this CONFIG is neither bool nor trisate
956 if old_val[-2:] != '=y' and old_val[-2:] != '=m' and old_val != not_set:
957 # tools/scripts/define2mk.sed changes '1' to 'y'.
958 # This is a problem if the CONFIG is int type.
959 # Check the type in Kconfig and handle it correctly.
960 if new_val[-2:] == '=y':
961 new_val = new_val[:-1] + '1'
963 return (ACTION_NO_CHANGE if old_val == new_val else ACTION_MOVE,
966 def update_dotconfig(self):
967 """Parse files for the config options and update the .config.
969 This function parses the generated .config and include/autoconf.mk
970 searching the target options.
971 Move the config option(s) to the .config as needed.
974 defconfig: defconfig name.
977 Return a tuple of (updated flag, log string).
978 The "updated flag" is True if the .config was updated, False
979 otherwise. The "log string" shows what happend to the .config.
985 rm_files = [self.config_autoconf, self.autoconf]
988 if os.path.exists(self.spl_autoconf):
989 autoconf_path = self.spl_autoconf
990 rm_files.append(self.spl_autoconf)
994 return (updated, suspicious,
995 color_text(self.options.color, COLOR_BROWN,
996 "SPL is not enabled. Skipped.") + '\n')
998 autoconf_path = self.autoconf
1000 with open(self.dotconfig) as f:
1001 dotconfig_lines = f.readlines()
1003 with open(autoconf_path) as f:
1004 autoconf_lines = f.readlines()
1006 for config in self.configs:
1007 result = self.parse_one_config(config, dotconfig_lines,
1009 results.append(result)
1013 for (action, value) in results:
1014 if action == ACTION_MOVE:
1015 actlog = "Move '%s'" % value
1016 log_color = COLOR_LIGHT_GREEN
1017 elif action == ACTION_NO_ENTRY:
1018 actlog = "%s is not defined in Kconfig. Do nothing." % value
1019 log_color = COLOR_LIGHT_BLUE
1020 elif action == ACTION_NO_ENTRY_WARN:
1021 actlog = "%s is not defined in Kconfig (suspicious). Do nothing." % value
1022 log_color = COLOR_YELLOW
1024 elif action == ACTION_NO_CHANGE:
1025 actlog = "'%s' is the same as the define in Kconfig. Do nothing." \
1027 log_color = COLOR_LIGHT_PURPLE
1028 elif action == ACTION_SPL_NOT_EXIST:
1029 actlog = "SPL is not enabled for this defconfig. Skip."
1030 log_color = COLOR_PURPLE
1032 sys.exit("Internal Error. This should not happen.")
1034 log += color_text(self.options.color, log_color, actlog) + '\n'
1036 with open(self.dotconfig, 'a') as f:
1037 for (action, value) in results:
1038 if action == ACTION_MOVE:
1039 f.write(value + '\n')
1042 self.results = results
1046 return (updated, suspicious, log)
1048 def check_defconfig(self):
1049 """Check the defconfig after savedefconfig
1052 Return additional log if moved CONFIGs were removed again by
1053 'make savedefconfig'.
1058 with open(self.defconfig) as f:
1059 defconfig_lines = f.readlines()
1061 for (action, value) in self.results:
1062 if action != ACTION_MOVE:
1064 if not value + '\n' in defconfig_lines:
1065 log += color_text(self.options.color, COLOR_YELLOW,
1066 "'%s' was removed by savedefconfig.\n" %
1072 class DatabaseThread(threading.Thread):
1073 """This thread processes results from Slot threads.
1075 It collects the data in the master config directary. There is only one
1076 result thread, and this helps to serialise the build output.
1078 def __init__(self, config_db, db_queue):
1079 """Set up a new result thread
1082 builder: Builder which will be sent each result
1084 threading.Thread.__init__(self)
1085 self.config_db = config_db
1086 self.db_queue= db_queue
1089 """Called to start up the result thread.
1091 We collect the next result job and pass it on to the build.
1094 defconfig, configs = self.db_queue.get()
1095 self.config_db[defconfig] = configs
1096 self.db_queue.task_done()
1101 """A slot to store a subprocess.
1103 Each instance of this class handles one subprocess.
1104 This class is useful to control multiple threads
1105 for faster processing.
1108 def __init__(self, configs, options, progress, devnull, make_cmd,
1109 reference_src_dir, db_queue):
1110 """Create a new process slot.
1113 configs: A list of CONFIGs to move.
1114 options: option flags.
1115 progress: A progress indicator.
1116 devnull: A file object of '/dev/null'.
1117 make_cmd: command name of GNU Make.
1118 reference_src_dir: Determine the true starting config state from this
1120 db_queue: output queue to write config info for the database
1122 self.options = options
1123 self.progress = progress
1124 self.build_dir = tempfile.mkdtemp()
1125 self.devnull = devnull
1126 self.make_cmd = (make_cmd, 'O=' + self.build_dir)
1127 self.reference_src_dir = reference_src_dir
1128 self.db_queue = db_queue
1129 self.parser = KconfigParser(configs, options, self.build_dir)
1130 self.state = STATE_IDLE
1131 self.failed_boards = set()
1132 self.suspicious_boards = set()
1135 """Delete the working directory
1137 This function makes sure the temporary directory is cleaned away
1138 even if Python suddenly dies due to error. It should be done in here
1139 because it is guaranteed the destructor is always invoked when the
1140 instance of the class gets unreferenced.
1142 If the subprocess is still running, wait until it finishes.
1144 if self.state != STATE_IDLE:
1145 while self.ps.poll() == None:
1147 shutil.rmtree(self.build_dir)
1149 def add(self, defconfig):
1150 """Assign a new subprocess for defconfig and add it to the slot.
1152 If the slot is vacant, create a new subprocess for processing the
1153 given defconfig and add it to the slot. Just returns False if
1154 the slot is occupied (i.e. the current subprocess is still running).
1157 defconfig: defconfig name.
1160 Return True on success or False on failure
1162 if self.state != STATE_IDLE:
1165 self.defconfig = defconfig
1167 self.current_src_dir = self.reference_src_dir
1172 """Check the status of the subprocess and handle it as needed.
1174 Returns True if the slot is vacant (i.e. in idle state).
1175 If the configuration is successfully finished, assign a new
1176 subprocess to build include/autoconf.mk.
1177 If include/autoconf.mk is generated, invoke the parser to
1178 parse the .config and the include/autoconf.mk, moving
1179 config options to the .config as needed.
1180 If the .config was updated, run "make savedefconfig" to sync
1181 it, update the original defconfig, and then set the slot back
1185 Return True if the subprocess is terminated, False otherwise
1187 if self.state == STATE_IDLE:
1190 if self.ps.poll() == None:
1193 if self.ps.poll() != 0:
1195 elif self.state == STATE_DEFCONFIG:
1196 if self.reference_src_dir and not self.current_src_dir:
1197 self.do_savedefconfig()
1200 elif self.state == STATE_AUTOCONF:
1201 if self.current_src_dir:
1202 self.current_src_dir = None
1204 elif self.options.build_db:
1207 self.do_savedefconfig()
1208 elif self.state == STATE_SAVEDEFCONFIG:
1209 self.update_defconfig()
1211 sys.exit("Internal Error. This should not happen.")
1213 return True if self.state == STATE_IDLE else False
1215 def handle_error(self):
1216 """Handle error cases."""
1218 self.log += color_text(self.options.color, COLOR_LIGHT_RED,
1219 "Failed to process.\n")
1220 if self.options.verbose:
1221 self.log += color_text(self.options.color, COLOR_LIGHT_CYAN,
1222 self.ps.stderr.read())
1225 def do_defconfig(self):
1226 """Run 'make <board>_defconfig' to create the .config file."""
1228 cmd = list(self.make_cmd)
1229 cmd.append(self.defconfig)
1230 self.ps = subprocess.Popen(cmd, stdout=self.devnull,
1231 stderr=subprocess.PIPE,
1232 cwd=self.current_src_dir)
1233 self.state = STATE_DEFCONFIG
1235 def do_autoconf(self):
1236 """Run 'make AUTO_CONF_PATH'."""
1238 self.cross_compile = self.parser.get_cross_compile()
1239 if self.cross_compile is None:
1240 self.log += color_text(self.options.color, COLOR_YELLOW,
1241 "Compiler is missing. Do nothing.\n")
1245 cmd = list(self.make_cmd)
1246 if self.cross_compile:
1247 cmd.append('CROSS_COMPILE=%s' % self.cross_compile)
1248 cmd.append('KCONFIG_IGNORE_DUPLICATES=1')
1249 cmd.append(AUTO_CONF_PATH)
1250 self.ps = subprocess.Popen(cmd, stdout=self.devnull,
1251 stderr=subprocess.PIPE,
1252 cwd=self.current_src_dir)
1253 self.state = STATE_AUTOCONF
1255 def do_build_db(self):
1256 """Add the board to the database"""
1258 with open(os.path.join(self.build_dir, AUTO_CONF_PATH)) as fd:
1259 for line in fd.readlines():
1260 if line.startswith('CONFIG'):
1261 config, value = line.split('=', 1)
1262 configs[config] = value.rstrip()
1263 self.db_queue.put([self.defconfig, configs])
1266 def do_savedefconfig(self):
1267 """Update the .config and run 'make savedefconfig'."""
1269 (updated, suspicious, log) = self.parser.update_dotconfig()
1271 self.suspicious_boards.add(self.defconfig)
1274 if not self.options.force_sync and not updated:
1278 self.log += color_text(self.options.color, COLOR_LIGHT_GREEN,
1279 "Syncing by savedefconfig...\n")
1281 self.log += "Syncing by savedefconfig (forced by option)...\n"
1283 cmd = list(self.make_cmd)
1284 cmd.append('savedefconfig')
1285 self.ps = subprocess.Popen(cmd, stdout=self.devnull,
1286 stderr=subprocess.PIPE)
1287 self.state = STATE_SAVEDEFCONFIG
1289 def update_defconfig(self):
1290 """Update the input defconfig and go back to the idle state."""
1292 log = self.parser.check_defconfig()
1294 self.suspicious_boards.add(self.defconfig)
1296 orig_defconfig = os.path.join('configs', self.defconfig)
1297 new_defconfig = os.path.join(self.build_dir, 'defconfig')
1298 updated = not filecmp.cmp(orig_defconfig, new_defconfig)
1301 self.log += color_text(self.options.color, COLOR_LIGHT_BLUE,
1302 "defconfig was updated.\n")
1304 if not self.options.dry_run and updated:
1305 shutil.move(new_defconfig, orig_defconfig)
1308 def finish(self, success):
1309 """Display log along with progress and go to the idle state.
1312 success: Should be True when the defconfig was processed
1313 successfully, or False when it fails.
1315 # output at least 30 characters to hide the "* defconfigs out of *".
1316 log = self.defconfig.ljust(30) + '\n'
1318 log += '\n'.join([ ' ' + s for s in self.log.split('\n') ])
1319 # Some threads are running in parallel.
1320 # Print log atomically to not mix up logs from different threads.
1321 print >> (sys.stdout if success else sys.stderr), log
1324 if self.options.exit_on_error:
1325 sys.exit("Exit on error.")
1326 # If --exit-on-error flag is not set, skip this board and continue.
1327 # Record the failed board.
1328 self.failed_boards.add(self.defconfig)
1331 self.progress.show()
1332 self.state = STATE_IDLE
1334 def get_failed_boards(self):
1335 """Returns a set of failed boards (defconfigs) in this slot.
1337 return self.failed_boards
1339 def get_suspicious_boards(self):
1340 """Returns a set of boards (defconfigs) with possible misconversion.
1342 return self.suspicious_boards - self.failed_boards
1346 """Controller of the array of subprocess slots."""
1348 def __init__(self, configs, options, progress, reference_src_dir, db_queue):
1349 """Create a new slots controller.
1352 configs: A list of CONFIGs to move.
1353 options: option flags.
1354 progress: A progress indicator.
1355 reference_src_dir: Determine the true starting config state from this
1357 db_queue: output queue to write config info for the database
1359 self.options = options
1361 devnull = get_devnull()
1362 make_cmd = get_make_cmd()
1363 for i in range(options.jobs):
1364 self.slots.append(Slot(configs, options, progress, devnull,
1365 make_cmd, reference_src_dir, db_queue))
1367 def add(self, defconfig):
1368 """Add a new subprocess if a vacant slot is found.
1371 defconfig: defconfig name to be put into.
1374 Return True on success or False on failure
1376 for slot in self.slots:
1377 if slot.add(defconfig):
1381 def available(self):
1382 """Check if there is a vacant slot.
1385 Return True if at lease one vacant slot is found, False otherwise.
1387 for slot in self.slots:
1393 """Check if all slots are vacant.
1396 Return True if all the slots are vacant, False otherwise.
1399 for slot in self.slots:
1404 def show_failed_boards(self):
1405 """Display all of the failed boards (defconfigs)."""
1407 output_file = 'moveconfig.failed'
1409 for slot in self.slots:
1410 boards |= slot.get_failed_boards()
1413 boards = '\n'.join(boards) + '\n'
1414 msg = "The following boards were not processed due to error:\n"
1416 msg += "(the list has been saved in %s)\n" % output_file
1417 print >> sys.stderr, color_text(self.options.color, COLOR_LIGHT_RED,
1420 with open(output_file, 'w') as f:
1423 def show_suspicious_boards(self):
1424 """Display all boards (defconfigs) with possible misconversion."""
1426 output_file = 'moveconfig.suspicious'
1428 for slot in self.slots:
1429 boards |= slot.get_suspicious_boards()
1432 boards = '\n'.join(boards) + '\n'
1433 msg = "The following boards might have been converted incorrectly.\n"
1434 msg += "It is highly recommended to check them manually:\n"
1436 msg += "(the list has been saved in %s)\n" % output_file
1437 print >> sys.stderr, color_text(self.options.color, COLOR_YELLOW,
1440 with open(output_file, 'w') as f:
1443 class ReferenceSource:
1445 """Reference source against which original configs should be parsed."""
1447 def __init__(self, commit):
1448 """Create a reference source directory based on a specified commit.
1451 commit: commit to git-clone
1453 self.src_dir = tempfile.mkdtemp()
1454 print "Cloning git repo to a separate work directory..."
1455 subprocess.check_output(['git', 'clone', os.getcwd(), '.'],
1457 print "Checkout '%s' to build the original autoconf.mk." % \
1458 subprocess.check_output(['git', 'rev-parse', '--short', commit]).strip()
1459 subprocess.check_output(['git', 'checkout', commit],
1460 stderr=subprocess.STDOUT, cwd=self.src_dir)
1463 """Delete the reference source directory
1465 This function makes sure the temporary directory is cleaned away
1466 even if Python suddenly dies due to error. It should be done in here
1467 because it is guaranteed the destructor is always invoked when the
1468 instance of the class gets unreferenced.
1470 shutil.rmtree(self.src_dir)
1473 """Return the absolute path to the reference source directory."""
1477 def move_config(configs, options, db_queue):
1478 """Move config options to defconfig files.
1481 configs: A list of CONFIGs to move.
1482 options: option flags
1484 if len(configs) == 0:
1485 if options.force_sync:
1486 print 'No CONFIG is specified. You are probably syncing defconfigs.',
1487 elif options.build_db:
1488 print 'Building %s database' % CONFIG_DATABASE
1490 print 'Neither CONFIG nor --force-sync is specified. Nothing will happen.',
1492 print 'Move ' + ', '.join(configs),
1493 print '(jobs: %d)\n' % options.jobs
1496 reference_src = ReferenceSource(options.git_ref)
1497 reference_src_dir = reference_src.get_dir()
1499 reference_src_dir = None
1501 if options.defconfigs:
1502 defconfigs = get_matched_defconfigs(options.defconfigs)
1504 defconfigs = get_all_defconfigs()
1506 progress = Progress(len(defconfigs))
1507 slots = Slots(configs, options, progress, reference_src_dir, db_queue)
1509 # Main loop to process defconfig files:
1510 # Add a new subprocess into a vacant slot.
1511 # Sleep if there is no available slot.
1512 for defconfig in defconfigs:
1513 while not slots.add(defconfig):
1514 while not slots.available():
1515 # No available slot: sleep for a while
1516 time.sleep(SLEEP_TIME)
1518 # wait until all the subprocesses finish
1519 while not slots.empty():
1520 time.sleep(SLEEP_TIME)
1523 slots.show_failed_boards()
1524 slots.show_suspicious_boards()
1526 def find_kconfig_rules(kconf, config, imply_config):
1527 """Check whether a config has a 'select' or 'imply' keyword
1530 kconf: Kconfig.Config object
1531 config: Name of config to check (without CONFIG_ prefix)
1532 imply_config: Implying config (without CONFIG_ prefix) which may or
1533 may not have an 'imply' for 'config')
1536 Symbol object for 'config' if found, else None
1538 sym = kconf.get_symbol(imply_config)
1540 for sel in sym.get_selected_symbols():
1541 if sel.get_name() == config:
1545 def check_imply_rule(kconf, config, imply_config):
1546 """Check if we can add an 'imply' option
1548 This finds imply_config in the Kconfig and looks to see if it is possible
1549 to add an 'imply' for 'config' to that part of the Kconfig.
1552 kconf: Kconfig.Config object
1553 config: Name of config to check (without CONFIG_ prefix)
1554 imply_config: Implying config (without CONFIG_ prefix) which may or
1555 may not have an 'imply' for 'config')
1559 filename of Kconfig file containing imply_config, or None if none
1560 line number within the Kconfig file, or 0 if none
1561 message indicating the result
1563 sym = kconf.get_symbol(imply_config)
1565 return 'cannot find sym'
1566 locs = sym.get_def_locations()
1568 return '%d locations' % len(locs)
1569 fname, linenum = locs[0]
1571 if cwd and fname.startswith(cwd):
1572 fname = fname[len(cwd) + 1:]
1573 file_line = ' at %s:%d' % (fname, linenum)
1574 with open(fname) as fd:
1575 data = fd.read().splitlines()
1576 if data[linenum - 1] != 'config %s' % imply_config:
1577 return None, 0, 'bad sym format %s%s' % (data[linenum], file_line)
1578 return fname, linenum, 'adding%s' % file_line
1580 def add_imply_rule(config, fname, linenum):
1581 """Add a new 'imply' option to a Kconfig
1584 config: config option to add an imply for (without CONFIG_ prefix)
1585 fname: Kconfig filename to update
1586 linenum: Line number to place the 'imply' before
1589 Message indicating the result
1591 file_line = ' at %s:%d' % (fname, linenum)
1592 data = open(fname).read().splitlines()
1595 for offset, line in enumerate(data[linenum:]):
1596 if line.strip().startswith('help') or not line:
1597 data.insert(linenum + offset, '\timply %s' % config)
1598 with open(fname, 'w') as fd:
1599 fd.write('\n'.join(data) + '\n')
1600 return 'added%s' % file_line
1602 return 'could not insert%s'
1604 (IMPLY_MIN_2, IMPLY_TARGET, IMPLY_CMD, IMPLY_NON_ARCH_BOARD) = (
1608 'min2': [IMPLY_MIN_2, 'Show options which imply >2 boards (normally >5)'],
1609 'target': [IMPLY_TARGET, 'Allow CONFIG_TARGET_... options to imply'],
1610 'cmd': [IMPLY_CMD, 'Allow CONFIG_CMD_... to imply'],
1612 IMPLY_NON_ARCH_BOARD,
1613 'Allow Kconfig options outside arch/ and /board/ to imply'],
1616 def do_imply_config(config_list, add_imply, imply_flags, skip_added,
1617 check_kconfig=True, find_superset=False):
1618 """Find CONFIG options which imply those in the list
1620 Some CONFIG options can be implied by others and this can help to reduce
1621 the size of the defconfig files. For example, CONFIG_X86 implies
1622 CONFIG_CMD_IRQ, so we can put 'imply CMD_IRQ' under 'config X86' and
1623 all x86 boards will have that option, avoiding adding CONFIG_CMD_IRQ to
1624 each of the x86 defconfig files.
1626 This function uses the moveconfig database to find such options. It
1627 displays a list of things that could possibly imply those in the list.
1628 The algorithm ignores any that start with CONFIG_TARGET since these
1629 typically refer to only a few defconfigs (often one). It also does not
1630 display a config with less than 5 defconfigs.
1632 The algorithm works using sets. For each target config in config_list:
1633 - Get the set 'defconfigs' which use that target config
1634 - For each config (from a list of all configs):
1635 - Get the set 'imply_defconfig' of defconfigs which use that config
1637 - If imply_defconfigs contains anything not in defconfigs then
1638 this config does not imply the target config
1641 config_list: List of CONFIG options to check (each a string)
1642 add_imply: Automatically add an 'imply' for each config.
1643 imply_flags: Flags which control which implying configs are allowed
1645 skip_added: Don't show options which already have an imply added.
1646 check_kconfig: Check if implied symbols already have an 'imply' or
1647 'select' for the target config, and show this information if so.
1648 find_superset: True to look for configs which are a superset of those
1649 already found. So for example if CONFIG_EXYNOS5 implies an option,
1650 but CONFIG_EXYNOS covers a larger set of defconfigs and also
1651 implies that option, this will drop the former in favour of the
1652 latter. In practice this option has not proved very used.
1654 Note the terminoloy:
1655 config - a CONFIG_XXX options (a string, e.g. 'CONFIG_CMD_EEPROM')
1656 defconfig - a defconfig file (a string, e.g. 'configs/snow_defconfig')
1658 kconf = KconfigScanner().conf if check_kconfig else None
1659 if add_imply and add_imply != 'all':
1660 add_imply = add_imply.split()
1662 # key is defconfig name, value is dict of (CONFIG_xxx, value)
1665 # Holds a dict containing the set of defconfigs that contain each config
1666 # key is config, value is set of defconfigs using that config
1667 defconfig_db = collections.defaultdict(set)
1669 # Set of all config options we have seen
1672 # Set of all defconfigs we have seen
1673 all_defconfigs = set()
1675 # Read in the database
1677 with open(CONFIG_DATABASE) as fd:
1678 for line in fd.readlines():
1679 line = line.rstrip()
1680 if not line: # Separator between defconfigs
1681 config_db[defconfig] = configs
1682 all_defconfigs.add(defconfig)
1684 elif line[0] == ' ': # CONFIG line
1685 config, value = line.strip().split('=', 1)
1686 configs[config] = value
1687 defconfig_db[config].add(defconfig)
1688 all_configs.add(config)
1689 else: # New defconfig
1692 # Work through each target config option in tern, independently
1693 for config in config_list:
1694 defconfigs = defconfig_db.get(config)
1696 print '%s not found in any defconfig' % config
1699 # Get the set of defconfigs without this one (since a config cannot
1701 non_defconfigs = all_defconfigs - defconfigs
1702 num_defconfigs = len(defconfigs)
1703 print '%s found in %d/%d defconfigs' % (config, num_defconfigs,
1706 # This will hold the results: key=config, value=defconfigs containing it
1708 rest_configs = all_configs - set([config])
1710 # Look at every possible config, except the target one
1711 for imply_config in rest_configs:
1712 if 'ERRATUM' in imply_config:
1714 if not (imply_flags & IMPLY_CMD):
1715 if 'CONFIG_CMD' in imply_config:
1717 if not (imply_flags & IMPLY_TARGET):
1718 if 'CONFIG_TARGET' in imply_config:
1721 # Find set of defconfigs that have this config
1722 imply_defconfig = defconfig_db[imply_config]
1724 # Get the intersection of this with defconfigs containing the
1726 common_defconfigs = imply_defconfig & defconfigs
1728 # Get the set of defconfigs containing this config which DO NOT
1729 # also contain the taret config. If this set is non-empty it means
1730 # that this config affects other defconfigs as well as (possibly)
1731 # the ones affected by the target config. This means it implies
1732 # things we don't want to imply.
1733 not_common_defconfigs = imply_defconfig & non_defconfigs
1734 if not_common_defconfigs:
1737 # If there are common defconfigs, imply_config may be useful
1738 if common_defconfigs:
1741 for prev in imply_configs.keys():
1742 prev_count = len(imply_configs[prev])
1743 count = len(common_defconfigs)
1744 if (prev_count > count and
1745 (imply_configs[prev] & common_defconfigs ==
1746 common_defconfigs)):
1747 # skip imply_config because prev is a superset
1750 elif count > prev_count:
1751 # delete prev because imply_config is a superset
1752 del imply_configs[prev]
1754 imply_configs[imply_config] = common_defconfigs
1756 # Now we have a dict imply_configs of configs which imply each config
1757 # The value of each dict item is the set of defconfigs containing that
1758 # config. Rank them so that we print the configs that imply the largest
1759 # number of defconfigs first.
1760 ranked_iconfigs = sorted(imply_configs,
1761 key=lambda k: len(imply_configs[k]), reverse=True)
1764 add_list = collections.defaultdict(list)
1765 for iconfig in ranked_iconfigs:
1766 num_common = len(imply_configs[iconfig])
1768 # Don't bother if there are less than 5 defconfigs affected.
1769 if num_common < (2 if imply_flags & IMPLY_MIN_2 else 5):
1771 missing = defconfigs - imply_configs[iconfig]
1772 missing_str = ', '.join(missing) if missing else 'all'
1776 sym = find_kconfig_rules(kconf, config[CONFIG_LEN:],
1777 iconfig[CONFIG_LEN:])
1780 locs = sym.get_def_locations()
1782 fname, linenum = locs[0]
1783 if cwd and fname.startswith(cwd):
1784 fname = fname[len(cwd) + 1:]
1785 kconfig_info = '%s:%d' % (fname, linenum)
1789 sym = kconf.get_symbol(iconfig[CONFIG_LEN:])
1792 locs = sym.get_def_locations()
1794 fname, linenum = locs[0]
1795 if cwd and fname.startswith(cwd):
1796 fname = fname[len(cwd) + 1:]
1797 in_arch_board = not sym or (fname.startswith('arch') or
1798 fname.startswith('board'))
1799 if (not in_arch_board and
1800 not (imply_flags & IMPLY_NON_ARCH_BOARD)):
1803 if add_imply and (add_imply == 'all' or
1804 iconfig in add_imply):
1805 fname, linenum, kconfig_info = (check_imply_rule(kconf,
1806 config[CONFIG_LEN:], iconfig[CONFIG_LEN:]))
1808 add_list[fname].append(linenum)
1810 if show and kconfig_info != 'skip':
1811 print '%5d : %-30s%-25s %s' % (num_common, iconfig.ljust(30),
1812 kconfig_info, missing_str)
1814 # Having collected a list of things to add, now we add them. We process
1815 # each file from the largest line number to the smallest so that
1816 # earlier additions do not affect our line numbers. E.g. if we added an
1817 # imply at line 20 it would change the position of each line after
1819 for fname, linenums in add_list.iteritems():
1820 for linenum in sorted(linenums, reverse=True):
1821 add_imply_rule(config[CONFIG_LEN:], fname, linenum)
1826 cpu_count = multiprocessing.cpu_count()
1827 except NotImplementedError:
1830 parser = optparse.OptionParser()
1832 parser.add_option('-a', '--add-imply', type='string', default='',
1833 help='comma-separated list of CONFIG options to add '
1834 "an 'imply' statement to for the CONFIG in -i")
1835 parser.add_option('-A', '--skip-added', action='store_true', default=False,
1836 help="don't show options which are already marked as "
1838 parser.add_option('-b', '--build-db', action='store_true', default=False,
1839 help='build a CONFIG database')
1840 parser.add_option('-c', '--color', action='store_true', default=False,
1841 help='display the log in color')
1842 parser.add_option('-C', '--commit', action='store_true', default=False,
1843 help='Create a git commit for the operation')
1844 parser.add_option('-d', '--defconfigs', type='string',
1845 help='a file containing a list of defconfigs to move, '
1846 "one per line (for example 'snow_defconfig') "
1847 "or '-' to read from stdin")
1848 parser.add_option('-i', '--imply', action='store_true', default=False,
1849 help='find options which imply others')
1850 parser.add_option('-I', '--imply-flags', type='string', default='',
1851 help="control the -i option ('help' for help")
1852 parser.add_option('-n', '--dry-run', action='store_true', default=False,
1853 help='perform a trial run (show log with no changes)')
1854 parser.add_option('-e', '--exit-on-error', action='store_true',
1856 help='exit immediately on any error')
1857 parser.add_option('-s', '--force-sync', action='store_true', default=False,
1858 help='force sync by savedefconfig')
1859 parser.add_option('-S', '--spl', action='store_true', default=False,
1860 help='parse config options defined for SPL build')
1861 parser.add_option('-H', '--headers-only', dest='cleanup_headers_only',
1862 action='store_true', default=False,
1863 help='only cleanup the headers')
1864 parser.add_option('-j', '--jobs', type='int', default=cpu_count,
1865 help='the number of jobs to run simultaneously')
1866 parser.add_option('-r', '--git-ref', type='string',
1867 help='the git ref to clone for building the autoconf.mk')
1868 parser.add_option('-y', '--yes', action='store_true', default=False,
1869 help="respond 'yes' to any prompts")
1870 parser.add_option('-v', '--verbose', action='store_true', default=False,
1871 help='show any build errors as boards are built')
1872 parser.usage += ' CONFIG ...'
1874 (options, configs) = parser.parse_args()
1876 if len(configs) == 0 and not any((options.force_sync, options.build_db,
1878 parser.print_usage()
1881 # prefix the option name with CONFIG_ if missing
1882 configs = [ config if config.startswith('CONFIG_') else 'CONFIG_' + config
1883 for config in configs ]
1885 check_top_directory()
1889 if options.imply_flags == 'all':
1892 elif options.imply_flags:
1893 for flag in options.imply_flags.split(','):
1894 bad = flag not in IMPLY_FLAGS
1896 print "Invalid flag '%s'" % flag
1897 if flag == 'help' or bad:
1898 print "Imply flags: (separate with ',')"
1899 for name, info in IMPLY_FLAGS.iteritems():
1900 print ' %-15s: %s' % (name, info[1])
1901 parser.print_usage()
1903 imply_flags |= IMPLY_FLAGS[flag][0]
1905 do_imply_config(configs, options.add_imply, imply_flags,
1910 db_queue = Queue.Queue()
1911 t = DatabaseThread(config_db, db_queue)
1915 if not options.cleanup_headers_only:
1916 check_clean_directory()
1917 update_cross_compile(options.color)
1918 move_config(configs, options, db_queue)
1922 cleanup_headers(configs, options)
1923 cleanup_extra_options(configs, options)
1924 cleanup_whitelist(configs, options)
1925 cleanup_readme(configs, options)
1928 subprocess.call(['git', 'add', '-u'])
1930 msg = 'Convert %s %sto Kconfig' % (configs[0],
1931 'et al ' if len(configs) > 1 else '')
1932 msg += ('\n\nThis converts the following to Kconfig:\n %s\n' %
1933 '\n '.join(configs))
1935 msg = 'configs: Resync with savedefconfig'
1936 msg += '\n\nRsync all defconfig files using moveconfig.py'
1937 subprocess.call(['git', 'commit', '-s', '-m', msg])
1939 if options.build_db:
1940 with open(CONFIG_DATABASE, 'w') as fd:
1941 for defconfig, configs in config_db.iteritems():
1942 print >>fd, '%s' % defconfig
1943 for config in sorted(configs.keys()):
1944 print >>fd, ' %s=%s' % (config, configs[config])
1947 if __name__ == '__main__':