From a535a371a9d06b3cfa696c8a67f15a621be3ec52 Mon Sep 17 00:00:00 2001 From: Simon Glass Date: Tue, 19 Sep 2023 20:05:48 -0600 Subject: dm: core: Adjust dump-sorting to get stats only when needed If we are not sorting the tree we don't need to get the stats. Adjust the code to avoid the wasted time. Signed-off-by: Simon Glass --- drivers/core/dump.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/drivers/core/dump.c b/drivers/core/dump.c index 4023b39..8411248 100644 --- a/drivers/core/dump.c +++ b/drivers/core/dump.c @@ -90,9 +90,8 @@ static void dm_dump_tree_single(struct udevice *dev, bool sort) int dev_count, uclasses; struct udevice **devs = NULL; - dm_get_stats(&dev_count, &uclasses); - if (sort) { + dm_get_stats(&dev_count, &uclasses); devs = calloc(dev_count, sizeof(struct udevice *)); if (!devs) { printf("(out of memory)\n"); -- cgit v1.1 From 63df202ad88fdd36deb8cd55eabe72db110962cb Mon Sep 17 00:00:00 2001 From: Simon Glass Date: Sat, 23 Sep 2023 13:43:50 -0600 Subject: moveconfig: Drop -H option Drop this option, which is no longer needed now that we have converted all CONFIG options to Kconfig. Signed-off-by: Simon Glass --- tools/moveconfig.py | 18 +++++++----------- 1 file changed, 7 insertions(+), 11 deletions(-) diff --git a/tools/moveconfig.py b/tools/moveconfig.py index 6cbecc3..880a559 100755 --- a/tools/moveconfig.py +++ b/tools/moveconfig.py @@ -1951,9 +1951,6 @@ doc/develop/moveconfig.rst for documentation.''' help='exit immediately on any error') parser.add_argument('-f', '--find', action='store_true', default=False, help='Find boards with a given config combination') - parser.add_argument('-H', '--headers-only', dest='cleanup_headers_only', - action='store_true', default=False, - help='only cleanup the headers') parser.add_argument('-i', '--imply', action='store_true', default=False, help='find options which imply others') parser.add_argument('-I', '--imply-flags', type=str, default='', @@ -2035,14 +2032,13 @@ doc/develop/moveconfig.rst for documentation.''' t.setDaemon(True) t.start() - if not args.cleanup_headers_only: - check_clean_directory() - bsettings.setup('') - toolchains = toolchain.Toolchains() - toolchains.GetSettings() - toolchains.Scan(verbose=False) - move_config(toolchains, configs, args, db_queue) - db_queue.join() + check_clean_directory() + bsettings.setup('') + toolchains = toolchain.Toolchains() + toolchains.GetSettings() + toolchains.Scan(verbose=False) + move_config(toolchains, configs, args, db_queue) + db_queue.join() if configs: cleanup_headers(configs, args) -- cgit v1.1 From ad1f187c18c65a3c0fe09c8a2dbba26ee8173098 Mon Sep 17 00:00:00 2001 From: Simon Glass Date: Sat, 23 Sep 2023 13:43:51 -0600 Subject: moveconfig: Avoid deprecation warning for setDaemon Use the recommended new way of setting a thread to be a daemon. This avoids a warning: DeprecationWarning: setDaemon() is deprecated, set the daemon attribute instead Signed-off-by: Simon Glass --- tools/moveconfig.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/moveconfig.py b/tools/moveconfig.py index 880a559..2f7dee8 100755 --- a/tools/moveconfig.py +++ b/tools/moveconfig.py @@ -2029,7 +2029,7 @@ doc/develop/moveconfig.rst for documentation.''' config_db = {} db_queue = queue.Queue() t = DatabaseThread(config_db, db_queue) - t.setDaemon(True) + t.daemon = True t.start() check_clean_directory() -- cgit v1.1 From b5aa5a32e99ae3c808e613e8a03cf9ad8aa7ff6e Mon Sep 17 00:00:00 2001 From: Simon Glass Date: Sat, 23 Sep 2023 13:43:52 -0600 Subject: moveconfig: Correct ordering of asteval import This should be after the standard imports. Move it to avoid a lot of pylint warnings. Signed-off-by: Simon Glass --- tools/moveconfig.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/moveconfig.py b/tools/moveconfig.py index 2f7dee8..a6dbda7 100755 --- a/tools/moveconfig.py +++ b/tools/moveconfig.py @@ -11,7 +11,6 @@ See doc/develop/moveconfig.rst for documentation. """ from argparse import ArgumentParser -import asteval import collections from contextlib import ExitStack import copy @@ -32,6 +31,7 @@ import threading import time import unittest +import asteval from buildman import bsettings from buildman import kconfiglib from buildman import toolchain -- cgit v1.1 From 3481e89d96be26c011496dc16c399676c118bd8f Mon Sep 17 00:00:00 2001 From: Simon Glass Date: Sat, 23 Sep 2023 13:43:53 -0600 Subject: moveconfig: Drop unused cleanup options Cleaning up the README and config.h files are not needed now, since we don't have any CONFIG options to convert. Drop this code. Signed-off-by: Simon Glass --- tools/moveconfig.py | 254 +--------------------------------------------------- 1 file changed, 2 insertions(+), 252 deletions(-) diff --git a/tools/moveconfig.py b/tools/moveconfig.py index a6dbda7..476603c 100755 --- a/tools/moveconfig.py +++ b/tools/moveconfig.py @@ -13,8 +13,6 @@ See doc/develop/moveconfig.rst for documentation. from argparse import ArgumentParser import collections from contextlib import ExitStack -import copy -import difflib import doctest import filecmp import fnmatch @@ -205,102 +203,6 @@ def color_text(color_enabled, color, string): for s in string.split('\n') ]) return string -def show_diff(alines, blines, file_path, color_enabled): - """Show unidified diff. - - Args: - alines (list of str): A list of lines (before) - blines (list of str): A list of lines (after) - file_path (str): Path to the file - color_enabled (bool): Display the diff in color - """ - diff = difflib.unified_diff(alines, blines, - fromfile=os.path.join('a', file_path), - tofile=os.path.join('b', file_path)) - - for line in diff: - if line.startswith('-') and not line.startswith('--'): - print(color_text(color_enabled, COLOR_RED, line)) - elif line.startswith('+') and not line.startswith('++'): - print(color_text(color_enabled, COLOR_GREEN, line)) - else: - print(line) - -def extend_matched_lines(lines, matched, pre_patterns, post_patterns, - extend_pre, extend_post): - """Extend matched lines if desired patterns are found before/after already - matched lines. - - Args: - lines (list of str): list of lines handled. - matched (list of int): list of line numbers that have been already - matched (will be updated by this function) - pre_patterns (list of re.Pattern): list of regular expression that should - be matched as preamble - post_patterns (list of re.Pattern): list of regular expression that should - be matched as postamble - extend_pre (bool): Add the line number of matched preamble to the matched - list - extend_post (bool): Add the line number of matched postamble to the - matched list - """ - extended_matched = [] - - j = matched[0] - - for i in matched: - if i == 0 or i < j: - continue - j = i - while j in matched: - j += 1 - if j >= len(lines): - break - - for pat in pre_patterns: - if pat.search(lines[i - 1]): - break - else: - # not matched - continue - - for pat in post_patterns: - if pat.search(lines[j]): - break - else: - # not matched - continue - - if extend_pre: - extended_matched.append(i - 1) - if extend_post: - extended_matched.append(j) - - matched += extended_matched - matched.sort() - -def confirm(args, prompt): - """Ask the user to confirm something - - Args: - args (Namespace ): program arguments - - Returns: - bool: True to confirm, False to cancel/stop - """ - if not args.yes: - while True: - choice = input(f'{prompt} [y/n]: ') - choice = choice.lower() - print(choice) - if choice in ('y', 'n'): - break - - if choice == 'n': - return False - - return True - def write_file(fname, data): """Write data to a file @@ -344,155 +246,6 @@ def read_file(fname, as_lines=True, skip_unicode=False): print("Failed on file %s': %s" % (fname, e)) return None -def cleanup_empty_blocks(header_path, args): - """Clean up empty conditional blocks - - Args: - header_path (str): path to the cleaned file. - args (Namespace): program arguments - """ - pattern = re.compile(r'^\s*#\s*if.*$\n^\s*#\s*endif.*$\n*', flags=re.M) - data = read_file(header_path, as_lines=False, skip_unicode=True) - if data is None: - return - - new_data = pattern.sub('\n', data) - - show_diff(data.splitlines(True), new_data.splitlines(True), header_path, - args.color) - - if args.dry_run: - return - - if new_data != data: - write_file(header_path, new_data) - -def cleanup_one_header(header_path, patterns, args): - """Clean regex-matched lines away from a file. - - Args: - header_path: path to the cleaned file. - patterns: list of regex patterns. Any lines matching to these - patterns are deleted. - args (Namespace): program arguments - """ - lines = read_file(header_path, skip_unicode=True) - if lines is None: - return - - matched = [] - for i, line in enumerate(lines): - if i - 1 in matched and lines[i - 1].endswith('\\'): - matched.append(i) - continue - for pattern in patterns: - if pattern.search(line): - matched.append(i) - break - - if not matched: - return - - # remove empty #ifdef ... #endif, successive blank lines - pattern_if = re.compile(r'#\s*if(def|ndef)?\b') # #if, #ifdef, #ifndef - pattern_elif = re.compile(r'#\s*el(if|se)\b') # #elif, #else - pattern_endif = re.compile(r'#\s*endif\b') # #endif - pattern_blank = re.compile(r'^\s*$') # empty line - - while True: - old_matched = copy.copy(matched) - extend_matched_lines(lines, matched, [pattern_if], - [pattern_endif], True, True) - extend_matched_lines(lines, matched, [pattern_elif], - [pattern_elif, pattern_endif], True, False) - extend_matched_lines(lines, matched, [pattern_if, pattern_elif], - [pattern_blank], False, True) - extend_matched_lines(lines, matched, [pattern_blank], - [pattern_elif, pattern_endif], True, False) - extend_matched_lines(lines, matched, [pattern_blank], - [pattern_blank], True, False) - if matched == old_matched: - break - - tolines = copy.copy(lines) - - for i in reversed(matched): - tolines.pop(i) - - show_diff(lines, tolines, header_path, args.color) - - if args.dry_run: - return - - write_file(header_path, tolines) - -def cleanup_headers(configs, args): - """Delete config defines from board headers. - - Args: - configs: A list of CONFIGs to remove. - args (Namespace): program arguments - """ - if not confirm(args, 'Clean up headers?'): - return - - patterns = [] - for config in configs: - patterns.append(re.compile(r'#\s*define\s+%s\b' % config)) - patterns.append(re.compile(r'#\s*undef\s+%s\b' % config)) - - for dir in 'include', 'arch', 'board': - for (dirpath, dirnames, filenames) in os.walk(dir): - if dirpath == os.path.join('include', 'generated'): - continue - for filename in filenames: - if not filename.endswith(('~', '.dts', '.dtsi', '.bin', - '.elf','.aml','.dat')): - header_path = os.path.join(dirpath, filename) - # This file contains UTF-16 data and no CONFIG symbols - if header_path == 'include/video_font_data.h': - continue - cleanup_one_header(header_path, patterns, args) - cleanup_empty_blocks(header_path, args) - -def find_matching(patterns, line): - for pat in patterns: - if pat.search(line): - return True - return False - -def cleanup_readme(configs, args): - """Delete config description in README - - Args: - configs: A list of CONFIGs to remove. - args (Namespace): program arguments - """ - if not confirm(args, 'Clean up README?'): - return - - patterns = [] - for config in configs: - patterns.append(re.compile(r'^\s+%s' % config)) - - lines = read_file('README') - - found = False - newlines = [] - for line in lines: - if not found: - found = find_matching(patterns, line) - if found: - continue - - if found and re.search(r'^\s+CONFIG', line): - found = False - - if not found: - newlines.append(line) - - write_file('README', newlines) - def try_expand(line): """If value looks like an expression, try expanding it Otherwise just return the existing value @@ -2026,6 +1779,7 @@ doc/develop/moveconfig.rst for documentation.''' do_find_config(configs) return + # We are either building the database or forcing a sync of defconfigs config_db = {} db_queue = queue.Queue() t = DatabaseThread(config_db, db_queue) @@ -2037,13 +1791,9 @@ doc/develop/moveconfig.rst for documentation.''' toolchains = toolchain.Toolchains() toolchains.GetSettings() toolchains.Scan(verbose=False) - move_config(toolchains, configs, args, db_queue) + move_config(toolchains, [], args, db_queue) db_queue.join() - if configs: - cleanup_headers(configs, args) - cleanup_readme(configs, args) - if args.commit: subprocess.call(['git', 'add', '-u']) if configs: -- cgit v1.1 From 882c8e479f5f56219500a29f477d5dcf3357544b Mon Sep 17 00:00:00 2001 From: Simon Glass Date: Sat, 23 Sep 2023 13:43:54 -0600 Subject: moveconfig: Drop CONFIG-moving code As a step towards cleaning out old code, drop most of the code that moves CONFIG options to Kconfig. This includes parse_one_config(). Drop the ACTION_... values as well, since they are no-longer used. Signed-off-by: Simon Glass --- tools/moveconfig.py | 163 ++++++---------------------------------------------- 1 file changed, 19 insertions(+), 144 deletions(-) diff --git a/tools/moveconfig.py b/tools/moveconfig.py index 476603c..a4e1600 100755 --- a/tools/moveconfig.py +++ b/tools/moveconfig.py @@ -42,11 +42,6 @@ STATE_DEFCONFIG = 1 STATE_AUTOCONF = 2 STATE_SAVEDEFCONFIG = 3 -ACTION_MOVE = 0 -ACTION_NO_ENTRY = 1 -ACTION_NO_ENTRY_WARN = 2 -ACTION_NO_CHANGE = 3 - COLOR_BLACK = '0;30' COLOR_RED = '0;31' COLOR_GREEN = '0;32' @@ -312,15 +307,13 @@ class KconfigParser: re_arch = re.compile(r'CONFIG_SYS_ARCH="(.*)"') re_cpu = re.compile(r'CONFIG_SYS_CPU="(.*)"') - def __init__(self, configs, args, build_dir): + def __init__(self, args, build_dir): """Create a new parser. Args: - configs: A list of CONFIGs to move. args (Namespace): program arguments build_dir: Build directory. """ - self.configs = configs self.args = args self.dotconfig = os.path.join(build_dir, '.config') self.autoconf = os.path.join(build_dir, 'include', 'autoconf.mk') @@ -355,56 +348,6 @@ class KconfigParser: return arch - def parse_one_config(self, config, dotconfig_lines, autoconf_lines): - """Parse .config, defconfig, include/autoconf.mk for one config. - - This function looks for the config options in the lines from - defconfig, .config, and include/autoconf.mk in order to decide - which action should be taken for this defconfig. - - Args: - config: CONFIG name to parse. - dotconfig_lines: lines from the .config file. - autoconf_lines: lines from the include/autoconf.mk file. - - Returns: - A tupple of the action for this defconfig and the line - matched for the config. - """ - not_set = '# %s is not set' % config - - for line in autoconf_lines: - line = line.rstrip() - if line.startswith(config + '='): - new_val = line - break - else: - new_val = not_set - - new_val = try_expand(new_val) - - for line in dotconfig_lines: - line = line.rstrip() - if line.startswith(config + '=') or line == not_set: - old_val = line - break - else: - if new_val == not_set: - return (ACTION_NO_ENTRY, config) - else: - return (ACTION_NO_ENTRY_WARN, config) - - # If this CONFIG is neither bool nor trisate - if old_val[-2:] != '=y' and old_val[-2:] != '=m' and old_val != not_set: - # tools/scripts/define2mk.sed changes '1' to 'y'. - # This is a problem if the CONFIG is int type. - # Check the type in Kconfig and handle it correctly. - if new_val[-2:] == '=y': - new_val = new_val[:-1] + '1' - - return (ACTION_NO_CHANGE if old_val == new_val else ACTION_MOVE, - new_val) - def update_dotconfig(self): """Parse files for the config options and update the .config. @@ -420,66 +363,17 @@ class KconfigParser: The "updated flag" is True if the .config was updated, False otherwise. The "log string" shows what happend to the .config. """ - - results = [] updated = False suspicious = False - rm_files = [self.config_autoconf, self.autoconf] - if self.args.spl: - if os.path.exists(self.spl_autoconf): - autoconf_path = self.spl_autoconf - rm_files.append(self.spl_autoconf) - else: - for f in rm_files: - os.remove(f) - return (updated, suspicious, - color_text(self.args.color, COLOR_BROWN, - "SPL is not enabled. Skipped.") + '\n') - else: - autoconf_path = self.autoconf + autoconf_path = self.autoconf dotconfig_lines = read_file(self.dotconfig) autoconf_lines = read_file(autoconf_path) - for config in self.configs: - result = self.parse_one_config(config, dotconfig_lines, - autoconf_lines) - results.append(result) - log = '' - for (action, value) in results: - if action == ACTION_MOVE: - actlog = "Move '%s'" % value - log_color = COLOR_LIGHT_GREEN - elif action == ACTION_NO_ENTRY: - actlog = '%s is not defined in Kconfig. Do nothing.' % value - log_color = COLOR_LIGHT_BLUE - elif action == ACTION_NO_ENTRY_WARN: - actlog = '%s is not defined in Kconfig (suspicious). Do nothing.' % value - log_color = COLOR_YELLOW - suspicious = True - elif action == ACTION_NO_CHANGE: - actlog = "'%s' is the same as the define in Kconfig. Do nothing." \ - % value - log_color = COLOR_LIGHT_PURPLE - else: - sys.exit('Internal Error. This should not happen.') - - log += color_text(self.args.color, log_color, actlog) + '\n' - - with open(self.dotconfig, 'a', encoding='utf-8') as out: - for (action, value) in results: - if action == ACTION_MOVE: - out.write(value + '\n') - updated = True - - self.results = results - for f in rm_files: - os.remove(f) - return (updated, suspicious, log) def check_defconfig(self): @@ -494,14 +388,6 @@ class KconfigParser: defconfig_lines = read_file(self.defconfig) - for (action, value) in self.results: - if action != ACTION_MOVE: - continue - if not value in defconfig_lines: - log += color_text(self.args.color, COLOR_YELLOW, - "'%s' was removed by savedefconfig.\n" % - value) - return log @@ -541,13 +427,12 @@ class Slot: for faster processing. """ - def __init__(self, toolchains, configs, args, progress, devnull, + def __init__(self, toolchains, args, progress, devnull, make_cmd, reference_src_dir, db_queue): """Create a new process slot. Args: toolchains: Toolchains object containing toolchains. - configs: A list of CONFIGs to move. args: Program arguments progress: A progress indicator. devnull: A file object of '/dev/null'. @@ -564,7 +449,7 @@ class Slot: self.make_cmd = (make_cmd, 'O=' + self.build_dir) self.reference_src_dir = reference_src_dir self.db_queue = db_queue - self.parser = KconfigParser(configs, args, self.build_dir) + self.parser = KconfigParser(args, self.build_dir) self.state = STATE_IDLE self.failed_boards = set() self.suspicious_boards = set() @@ -783,13 +668,11 @@ class Slots: """Controller of the array of subprocess slots.""" - def __init__(self, toolchains, configs, args, progress, - reference_src_dir, db_queue): + def __init__(self, toolchains, args, progress, reference_src_dir, db_queue): """Create a new slots controller. Args: toolchains: Toolchains object containing toolchains. - configs: A list of CONFIGs to move. args: Program arguments progress: A progress indicator. reference_src_dir: Determine the true starting config state from this @@ -801,9 +684,8 @@ class Slots: devnull = subprocess.DEVNULL make_cmd = get_make_cmd() for i in range(args.jobs): - self.slots.append(Slot(toolchains, configs, args, progress, - devnull, make_cmd, reference_src_dir, - db_queue)) + self.slots.append(Slot(toolchains, args, progress, devnull, + make_cmd, reference_src_dir, db_queue)) def add(self, defconfig): """Add a new subprocess if a vacant slot is found. @@ -913,22 +795,18 @@ class ReferenceSource: return self.src_dir -def move_config(toolchains, configs, args, db_queue): - """Move config options to defconfig files. +def move_config(toolchains, args, db_queue): + """Build database or sync config options to defconfig files. Args: - configs: A list of CONFIGs to move. + toolchains: Toolchains to use args: Program arguments + db_queue: Queue for database updates """ - if len(configs) == 0: - if args.force_sync: - print('No CONFIG is specified. You are probably syncing defconfigs.', end=' ') - elif args.build_db: - print('Building %s database' % CONFIG_DATABASE) - else: - print('Neither CONFIG nor --force-sync is specified. Nothing will happen.', end=' ') - else: - print('Move ' + ', '.join(configs), end=' ') + if args.force_sync: + print('Syncing defconfigs', end=' ') + elif args.build_db: + print('Building %s database' % CONFIG_DATABASE) print('(jobs: %d)\n' % args.jobs) if args.git_ref: @@ -943,8 +821,7 @@ def move_config(toolchains, configs, args, db_queue): defconfigs = get_all_defconfigs() progress = Progress(len(defconfigs)) - slots = Slots(toolchains, configs, args, progress, reference_src_dir, - db_queue) + slots = Slots(toolchains, args, progress, reference_src_dir, db_queue) # Main loop to process defconfig files: # Add a new subprocess into a vacant slot. @@ -1731,7 +1608,6 @@ doc/develop/moveconfig.rst for documentation.''' parser.add_argument('configs', nargs='*') args = parser.parse_args() - configs = args.configs if args.test: sys.argv = [sys.argv[0]] @@ -1744,13 +1620,12 @@ doc/develop/moveconfig.rst for documentation.''' do_scan_source(os.getcwd(), args.update) return - if not any((len(configs), args.force_sync, args.build_db, args.imply, - args.find)): + if not any((args.force_sync, args.build_db, args.imply, args.find)): parser.print_usage() sys.exit(1) # prefix the option name with CONFIG_ if missing - configs = [prefix_config(cfg) for cfg in configs] + configs = [prefix_config(cfg) for cfg in args.configs] check_top_directory() @@ -1791,7 +1666,7 @@ doc/develop/moveconfig.rst for documentation.''' toolchains = toolchain.Toolchains() toolchains.GetSettings() toolchains.Scan(verbose=False) - move_config(toolchains, [], args, db_queue) + move_config(toolchains, args, db_queue) db_queue.join() if args.commit: -- cgit v1.1 From c734561563dd0e02b0d1f3b2a7085579d2e4d718 Mon Sep 17 00:00:00 2001 From: Simon Glass Date: Sat, 23 Sep 2023 13:43:55 -0600 Subject: moveconfig: Drop check_defconfig() and update_dotconfig() These functions are not needed anymore. Drop them. Signed-off-by: Simon Glass --- tools/moveconfig.py | 62 ++--------------------------------------------------- 1 file changed, 2 insertions(+), 60 deletions(-) diff --git a/tools/moveconfig.py b/tools/moveconfig.py index a4e1600..87a670f 100755 --- a/tools/moveconfig.py +++ b/tools/moveconfig.py @@ -348,48 +348,6 @@ class KconfigParser: return arch - def update_dotconfig(self): - """Parse files for the config options and update the .config. - - This function parses the generated .config and include/autoconf.mk - searching the target options. - Move the config option(s) to the .config as needed. - - Args: - defconfig: defconfig name. - - Returns: - Return a tuple of (updated flag, log string). - The "updated flag" is True if the .config was updated, False - otherwise. The "log string" shows what happend to the .config. - """ - updated = False - suspicious = False - - autoconf_path = self.autoconf - - dotconfig_lines = read_file(self.dotconfig) - - autoconf_lines = read_file(autoconf_path) - - log = '' - - return (updated, suspicious, log) - - def check_defconfig(self): - """Check the defconfig after savedefconfig - - Returns: - Return additional log if moved CONFIGs were removed again by - 'make savedefconfig'. - """ - - log = '' - - defconfig_lines = read_file(self.defconfig) - - return log - class DatabaseThread(threading.Thread): """This thread processes results from Slot threads. @@ -452,7 +410,6 @@ class Slot: self.parser = KconfigParser(args, self.build_dir) self.state = STATE_IDLE self.failed_boards = set() - self.suspicious_boards = set() def __del__(self): """Delete the working directory @@ -588,20 +545,10 @@ class Slot: def do_savedefconfig(self): """Update the .config and run 'make savedefconfig'.""" - - (updated, suspicious, log) = self.parser.update_dotconfig() - if suspicious: - self.suspicious_boards.add(self.defconfig) - self.log += log - - if not self.args.force_sync and not updated: + if not self.args.force_sync: self.finish(True) return - if updated: - self.log += color_text(self.args.color, COLOR_LIGHT_GREEN, - 'Syncing by savedefconfig...\n') - else: - self.log += 'Syncing by savedefconfig (forced by option)...\n' + self.log += 'Syncing by savedefconfig (forced by option)...\n' cmd = list(self.make_cmd) cmd.append('savedefconfig') @@ -611,11 +558,6 @@ class Slot: def update_defconfig(self): """Update the input defconfig and go back to the idle state.""" - - log = self.parser.check_defconfig() - if log: - self.suspicious_boards.add(self.defconfig) - self.log += log orig_defconfig = os.path.join('configs', self.defconfig) new_defconfig = os.path.join(self.build_dir, 'defconfig') updated = not filecmp.cmp(orig_defconfig, new_defconfig) -- cgit v1.1 From 03137421f5c89d6f3864b3261890670b52bdfb65 Mon Sep 17 00:00:00 2001 From: Simon Glass Date: Sat, 23 Sep 2023 13:43:56 -0600 Subject: moveconfig: Drop suspicious boards This code isn't needed anymore. Drop it. Signed-off-by: Simon Glass --- tools/moveconfig.py | 25 ------------------------- 1 file changed, 25 deletions(-) diff --git a/tools/moveconfig.py b/tools/moveconfig.py index 87a670f..36202fe 100755 --- a/tools/moveconfig.py +++ b/tools/moveconfig.py @@ -601,11 +601,6 @@ class Slot: """ return self.failed_boards - def get_suspicious_boards(self): - """Returns a set of boards (defconfigs) with possible misconversion. - """ - return self.suspicious_boards - self.failed_boards - class Slots: """Controller of the array of subprocess slots.""" @@ -684,25 +679,6 @@ class Slots: write_file(output_file, boards) - def show_suspicious_boards(self): - """Display all boards (defconfigs) with possible misconversion.""" - boards = set() - output_file = 'moveconfig.suspicious' - - for slot in self.slots: - boards |= slot.get_suspicious_boards() - - if boards: - boards = '\n'.join(boards) + '\n' - msg = 'The following boards might have been converted incorrectly.\n' - msg += 'It is highly recommended to check them manually:\n' - msg += boards - msg += '(the list has been saved in %s)\n' % output_file - print(color_text(self.args.color, COLOR_YELLOW, - msg), file=sys.stderr) - - write_file(output_file, boards) - class ReferenceSource: """Reference source against which original configs should be parsed.""" @@ -780,7 +756,6 @@ def move_config(toolchains, args, db_queue): print('') slots.show_failed_boards() - slots.show_suspicious_boards() def find_kconfig_rules(kconf, config, imply_config): """Check whether a config has a 'select' or 'imply' keyword -- cgit v1.1 From 98275712404a513649e8de5332c69a801ad3a743 Mon Sep 17 00:00:00 2001 From: Simon Glass Date: Sat, 23 Sep 2023 13:43:57 -0600 Subject: moveconfig: Correct some regular-expression strings Use the 'r' prefix for these strings to avoid pylint warnings. Signed-off-by: Simon Glass --- tools/moveconfig.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/tools/moveconfig.py b/tools/moveconfig.py index 36202fe..0b0ce64 100755 --- a/tools/moveconfig.py +++ b/tools/moveconfig.py @@ -1153,10 +1153,10 @@ def prefix_config(cfg): return op + cfg -RE_MK_CONFIGS = re.compile('CONFIG_(\$\(SPL_(?:TPL_)?\))?([A-Za-z0-9_]*)') -RE_IFDEF = re.compile('(ifdef|ifndef)') -RE_C_CONFIGS = re.compile('CONFIG_([A-Za-z0-9_]*)') -RE_CONFIG_IS = re.compile('CONFIG_IS_ENABLED\(([A-Za-z0-9_]*)\)') +RE_MK_CONFIGS = re.compile(r'CONFIG_(\$\(SPL_(?:TPL_)?\))?([A-Za-z0-9_]*)') +RE_IFDEF = re.compile(r'(ifdef|ifndef)') +RE_C_CONFIGS = re.compile(r'CONFIG_([A-Za-z0-9_]*)') +RE_CONFIG_IS = re.compile(r'CONFIG_IS_ENABLED\(([A-Za-z0-9_]*)\)') class ConfigUse: def __init__(self, cfg, is_spl, fname, rest): -- cgit v1.1 From 549d42230cd76b08f55d2b2070b9be0e12db9e13 Mon Sep 17 00:00:00 2001 From: Simon Glass Date: Sat, 23 Sep 2023 13:43:58 -0600 Subject: moveconfig: Correct parameter-type warnings Fix pylint warnings related to parameter types. Signed-off-by: Simon Glass --- tools/moveconfig.py | 43 ++++++++++++++++++++++--------------------- 1 file changed, 22 insertions(+), 21 deletions(-) diff --git a/tools/moveconfig.py b/tools/moveconfig.py index 0b0ce64..689018d 100755 --- a/tools/moveconfig.py +++ b/tools/moveconfig.py @@ -218,7 +218,7 @@ def read_file(fname, as_lines=True, skip_unicode=False): Args: fname (str): Filename to read from - as_lines: Return file contents as a list of lines + as_lines (bool): Return file contents as a list of lines skip_unicode (bool): True to report unicode errors and continue Returns: @@ -434,7 +434,7 @@ class Slot: the slot is occupied (i.e. the current subprocess is still running). Args: - defconfig: defconfig name. + defconfig (str): defconfig name. Returns: Return True on success or False on failure @@ -574,7 +574,7 @@ class Slot: """Display log along with progress and go to the idle state. Args: - success: Should be True when the defconfig was processed + success (bool): Should be True when the defconfig was processed successfully, or False when it fails. """ # output at least 30 characters to hide the "* defconfigs out of *". @@ -628,7 +628,7 @@ class Slots: """Add a new subprocess if a vacant slot is found. Args: - defconfig: defconfig name to be put into. + defconfig (str): defconfig name to be put into. Returns: Return True on success or False on failure @@ -717,9 +717,9 @@ def move_config(toolchains, args, db_queue): """Build database or sync config options to defconfig files. Args: - toolchains: Toolchains to use - args: Program arguments - db_queue: Queue for database updates + toolchains (Toolchains): Toolchains to use + args (Namespace): Program arguments + db_queue (Queue): Queue for database updates """ if args.force_sync: print('Syncing defconfigs', end=' ') @@ -761,10 +761,10 @@ def find_kconfig_rules(kconf, config, imply_config): """Check whether a config has a 'select' or 'imply' keyword Args: - kconf: Kconfiglib.Kconfig object - config: Name of config to check (without CONFIG_ prefix) - imply_config: Implying config (without CONFIG_ prefix) which may or - may not have an 'imply' for 'config') + kconf (Kconfiglib.Kconfig): Kconfig object + config (str): Name of config to check (without CONFIG_ prefix) + imply_config (str): Implying config (without CONFIG_ prefix) which may + or may not have an 'imply' for 'config') Returns: Symbol object for 'config' if found, else None @@ -783,16 +783,17 @@ def check_imply_rule(kconf, config, imply_config): to add an 'imply' for 'config' to that part of the Kconfig. Args: - kconf: Kconfiglib.Kconfig object - config: Name of config to check (without CONFIG_ prefix) - imply_config: Implying config (without CONFIG_ prefix) which may or - may not have an 'imply' for 'config') + kconf (Kconfiglib.Kconfig): Kconfig object + config (str): Name of config to check (without CONFIG_ prefix) + imply_config (str): Implying config (without CONFIG_ prefix) which may + or may not have an 'imply' for 'config') Returns: tuple: - filename of Kconfig file containing imply_config, or None if none - line number within the Kconfig file, or 0 if none - message indicating the result + str: filename of Kconfig file containing imply_config, or None if + none + int: line number within the Kconfig file, or 0 if none + str: message indicating the result """ sym = kconf.syms.get(imply_config) if not sym: @@ -815,9 +816,9 @@ def add_imply_rule(config, fname, linenum): """Add a new 'imply' option to a Kconfig Args: - config: config option to add an imply for (without CONFIG_ prefix) - fname: Kconfig filename to update - linenum: Line number to place the 'imply' before + config (str): config option to add an imply for (without CONFIG_ prefix) + fname (str): Kconfig filename to update + linenum (int): Line number to place the 'imply' before Returns: Message indicating the result -- cgit v1.1 From 1bd43060b3eec82bc9544c3acce8d7c6e2d75761 Mon Sep 17 00:00:00 2001 From: Simon Glass Date: Sat, 23 Sep 2023 13:43:59 -0600 Subject: moveconfig: Use f strings where possible Avoid pylint warnings by using 'f' strings where possible. Signed-off-by: Simon Glass --- tools/moveconfig.py | 56 ++++++++++++++++++++++++++--------------------------- 1 file changed, 28 insertions(+), 28 deletions(-) diff --git a/tools/moveconfig.py b/tools/moveconfig.py index 689018d..42298dd 100755 --- a/tools/moveconfig.py +++ b/tools/moveconfig.py @@ -238,7 +238,7 @@ def read_file(fname, as_lines=True, skip_unicode=False): except UnicodeDecodeError as e: if not skip_unicode: raise - print("Failed on file %s': %s" % (fname, e)) + print(f"Failed on file '{fname}: {e}") return None def try_expand(line): @@ -254,10 +254,10 @@ def try_expand(line): val= val.strip('\"') if re.search(r'[*+-/]|<<|SZ_+|\(([^\)]+)\)', val): newval = hex(aeval(val)) - print('\tExpanded expression %s to %s' % (val, newval)) + print(f'\tExpanded expression {val} to {newval}') return cfg+'='+newval except: - print('\tFailed to expand expression in %s' % line) + print(f'\tFailed to expand expression in {line}') return line @@ -283,7 +283,7 @@ class Progress: def show(self): """Display the progress.""" - print(' %d defconfigs out of %d\r' % (self.current, self.total), end=' ') + print(f' {self.current} defconfigs out of {self.total}\r', end=' ') sys.stdout.flush() @@ -520,7 +520,7 @@ class Slot: toolchain = self.toolchains.Select(arch) except ValueError: self.log += color_text(self.args.color, COLOR_YELLOW, - "Tool chain for '%s' is missing. Do nothing.\n" % arch) + f"Tool chain for '{arch}' is missing. Do nothing.\n") self.finish(False) return env = toolchain.MakeEnvironment(False) @@ -673,7 +673,7 @@ class Slots: boards = '\n'.join(boards) + '\n' msg = 'The following boards were not processed due to error:\n' msg += boards - msg += '(the list has been saved in %s)\n' % output_file + msg += f'(the list has been saved in {output_file})\n' print(color_text(self.args.color, COLOR_LIGHT_RED, msg), file=sys.stderr) @@ -693,8 +693,9 @@ class ReferenceSource: print('Cloning git repo to a separate work directory...') subprocess.check_output(['git', 'clone', os.getcwd(), '.'], cwd=self.src_dir) - print("Checkout '%s' to build the original autoconf.mk." % \ - subprocess.check_output(['git', 'rev-parse', '--short', commit]).strip()) + rev = subprocess.check_output(['git', 'rev-parse', '--short', + commit]).strip() + print(f"Checkout '{rev}' to build the original autoconf.mk.") subprocess.check_output(['git', 'checkout', commit], stderr=subprocess.STDOUT, cwd=self.src_dir) @@ -724,8 +725,8 @@ def move_config(toolchains, args, db_queue): if args.force_sync: print('Syncing defconfigs', end=' ') elif args.build_db: - print('Building %s database' % CONFIG_DATABASE) - print('(jobs: %d)\n' % args.jobs) + print(f'Building {CONFIG_DATABASE} database') + print(f'(jobs: {args.jobs})\n') if args.git_ref: reference_src = ReferenceSource(args.git_ref) @@ -800,17 +801,17 @@ def check_imply_rule(kconf, config, imply_config): return 'cannot find sym' nodes = sym.nodes if len(nodes) != 1: - return '%d locations' % len(nodes) + return f'{len(nodes)} locations' node = nodes[0] fname, linenum = node.filename, node.linenr cwd = os.getcwd() if cwd and fname.startswith(cwd): fname = fname[len(cwd) + 1:] - file_line = ' at %s:%d' % (fname, linenum) + file_line = f' at {fname}:{linenum}' data = read_file(fname) - if data[linenum - 1] != 'config %s' % imply_config: - return None, 0, 'bad sym format %s%s' % (data[linenum], file_line) - return fname, linenum, 'adding%s' % file_line + if data[linenum - 1] != f'config {imply_config}': + return None, 0, f'bad sym format {data[linenum]}{file_line})' + return fname, linenum, f'adding{file_line}' def add_imply_rule(config, fname, linenum): """Add a new 'imply' option to a Kconfig @@ -823,15 +824,15 @@ def add_imply_rule(config, fname, linenum): Returns: Message indicating the result """ - file_line = ' at %s:%d' % (fname, linenum) + file_line = f' at {fname}:{linenum}' data = read_file(fname) linenum -= 1 for offset, line in enumerate(data[linenum:]): if line.strip().startswith('help') or not line: - data.insert(linenum + offset, '\timply %s' % config) + data.insert(linenum + offset, f'\timply {config}') write_file(fname, data) - return 'added%s' % file_line + return f'added{file_line}' return 'could not insert%s' @@ -946,15 +947,14 @@ def do_imply_config(config_list, add_imply, imply_flags, skip_added, for config in config_list: defconfigs = defconfig_db.get(config) if not defconfigs: - print('%s not found in any defconfig' % config) + print(f'{config} not found in any defconfig') continue # Get the set of defconfigs without this one (since a config cannot # imply itself) non_defconfigs = all_defconfigs - defconfigs num_defconfigs = len(defconfigs) - print('%s found in %d/%d defconfigs' % (config, num_defconfigs, - len(all_configs))) + print(f'{config} found in {num_defconfigs}/{len(all_configs)} defconfigs') # This will hold the results: key=config, value=defconfigs containing it imply_configs = {} @@ -1035,7 +1035,7 @@ def do_imply_config(config_list, add_imply, imply_flags, skip_added, fname, linenum = nodes[0].filename, nodes[0].linenr if cwd and fname.startswith(cwd): fname = fname[len(cwd) + 1:] - kconfig_info = '%s:%d' % (fname, linenum) + kconfig_info = f'{fname}:{linenum}' if skip_added: show = False else: @@ -1061,8 +1061,8 @@ def do_imply_config(config_list, add_imply, imply_flags, skip_added, add_list[fname].append(linenum) if show and kconfig_info != 'skip': - print('%5d : %-30s%-25s %s' % (num_common, iconfig.ljust(30), - kconfig_info, missing_str)) + print(f'{num_common:5d} : ' + f'{iconfig.ljust(30):-30s}{kconfig_info:-25s} {missing_str}') # Having collected a list of things to add, now we add them. We process # each file from the largest line number to the smallest so that @@ -1556,11 +1556,11 @@ doc/develop/moveconfig.rst for documentation.''' for flag in args.imply_flags.split(','): bad = flag not in IMPLY_FLAGS if bad: - print("Invalid flag '%s'" % flag) + print(f"Invalid flag '{flag}'") if flag == 'help' or bad: print("Imply flags: (separate with ',')") for name, info in IMPLY_FLAGS.items(): - print(' %-15s: %s' % (name, info[1])) + print(f' {name:-15s}: {info[1]}') parser.print_usage() sys.exit(1) imply_flags |= IMPLY_FLAGS[flag][0] @@ -1602,9 +1602,9 @@ doc/develop/moveconfig.rst for documentation.''' if args.build_db: with open(CONFIG_DATABASE, 'w', encoding='utf-8') as fd: for defconfig, configs in config_db.items(): - fd.write('%s\n' % defconfig) + fd.write(f'{defconfig}\n') for config in sorted(configs.keys()): - fd.write(' %s=%s\n' % (config, configs[config])) + fd.write(f' {config}={configs[config]}\n') fd.write('\n') if __name__ == '__main__': -- cgit v1.1 From 62fae4bf66a69738d7621b099a4d91aed70973b8 Mon Sep 17 00:00:00 2001 From: Simon Glass Date: Sat, 23 Sep 2023 13:44:00 -0600 Subject: moveconfig: Correct unused variables Fix pylint warnings about unused variables. Signed-off-by: Simon Glass --- tools/moveconfig.py | 26 ++++++++++++-------------- 1 file changed, 12 insertions(+), 14 deletions(-) diff --git a/tools/moveconfig.py b/tools/moveconfig.py index 42298dd..911e272 100755 --- a/tools/moveconfig.py +++ b/tools/moveconfig.py @@ -620,7 +620,7 @@ class Slots: self.slots = [] devnull = subprocess.DEVNULL make_cmd = get_make_cmd() - for i in range(args.jobs): + for _ in range(args.jobs): self.slots.append(Slot(toolchains, args, progress, devnull, make_cmd, reference_src_dir, db_queue)) @@ -772,7 +772,7 @@ def find_kconfig_rules(kconf, config, imply_config): """ sym = kconf.syms.get(imply_config) if sym: - for sel, cond in (sym.selects + sym.implies): + for sel, _ in (sym.selects + sym.implies): if sel.name == config: return sym return None @@ -941,7 +941,7 @@ def do_imply_config(config_list, add_imply, imply_flags, skip_added, if add_imply and add_imply != 'all': add_imply = add_imply.split(',') - all_configs, all_defconfigs, config_db, defconfig_db = read_database() + all_configs, all_defconfigs, _, defconfig_db = read_database() # Work through each target config option in turn, independently for config in config_list: @@ -1101,7 +1101,7 @@ def do_find_config(config_list): is preceded by a tilde (~) then it must be false, otherwise it must be true) """ - all_configs, all_defconfigs, config_db, defconfig_db = read_database() + _, all_defconfigs, config_db, _ = read_database() # Start with all defconfigs out = all_defconfigs @@ -1199,9 +1199,7 @@ def scan_makefiles(fnames): fname_uses = {} for fname, rest in fnames: m_iter = RE_MK_CONFIGS.finditer(rest) - found = False for m in m_iter: - found = True real_opt = m.group(2) if real_opt == '': continue @@ -1242,9 +1240,11 @@ def scan_src_files(fnames): >>> RE_CONFIG_IS.search('#if CONFIG_IS_ENABLED(OF_PLATDATA)').groups() ('OF_PLATDATA',) """ + fname = None + rest = None + def add_uses(m_iter, is_spl): for m in m_iter: - found = True real_opt = m.group(1) if real_opt == '': continue @@ -1302,7 +1302,7 @@ def do_scan_source(path, do_update): """ # Make sure we know about all the options not_found = collections.defaultdict(list) - for use, rest in all_uses.items(): + for use, _ in all_uses.items(): name = use.cfg if name in IGNORE_SYMS: continue @@ -1314,7 +1314,6 @@ def do_scan_source(path, do_update): # If it is an SPL symbol, try prepending all SPL_ prefixes to # find at least one SPL symbol if use.is_spl: - add_to_dict = False for prefix in SPL_PREFIXES: try_name = prefix + name sym = kconf.syms.get(try_name) @@ -1332,7 +1331,6 @@ def do_scan_source(path, do_update): elif not use.is_spl: check = False else: # MODE_NORMAL - debug = False sym = kconf.syms.get(name) if not sym: proper_name = is_not_proper(name) @@ -1373,7 +1371,7 @@ def do_scan_source(path, do_update): print(f'Scanning source in {path}') args = ['git', 'grep', '-E', r'IS_ENABLED|\bCONFIG'] with subprocess.Popen(args, stdout=subprocess.PIPE) as proc: - out, err = proc.communicate() + out, _ = proc.communicate() lines = out.splitlines() re_fname = re.compile('^([^:]*):(.*)') src_list = [] @@ -1407,7 +1405,7 @@ def do_scan_source(path, do_update): print(f'Not sure how to handle file {fname}') # Scan the Makefiles - all_uses, fname_uses = scan_makefiles(mk_list) + all_uses, _ = scan_makefiles(mk_list) spl_not_found = set() proper_not_found = set() @@ -1428,7 +1426,7 @@ def do_scan_source(path, do_update): proper_not_found |= set([key for key in not_found.keys()]) # Scan the source code - all_uses, fname_uses = scan_src_files(src_list) + all_uses, _ = scan_src_files(src_list) # Make sure we know about all the options print('\nCONFIG options present in source but not Kconfig:') @@ -1529,7 +1527,7 @@ doc/develop/moveconfig.rst for documentation.''' if args.test: sys.argv = [sys.argv[0]] - fail, count = doctest.testmod() + fail, _ = doctest.testmod() if fail: return 1 unittest.main() -- cgit v1.1 From a4c9d178bc346d8cb1a8baa17f7207564076710e Mon Sep 17 00:00:00 2001 From: Simon Glass Date: Sat, 23 Sep 2023 13:44:01 -0600 Subject: moveconfig: Correct non-snake variables names Correct some variable names that do not conform to snake case, with the three-character minimum. Signed-off-by: Simon Glass --- tools/moveconfig.py | 70 ++++++++++++++++++++++++++--------------------------- 1 file changed, 35 insertions(+), 35 deletions(-) diff --git a/tools/moveconfig.py b/tools/moveconfig.py index 911e272..2234f28 100755 --- a/tools/moveconfig.py +++ b/tools/moveconfig.py @@ -235,10 +235,10 @@ def read_file(fname, as_lines=True, skip_unicode=False): return [line.rstrip('\n') for line in inf.readlines()] else: return inf.read() - except UnicodeDecodeError as e: + except UnicodeDecodeError as exc: if not skip_unicode: raise - print(f"Failed on file '{fname}: {e}") + print(f"Failed on file '{fname}: {exc}") return None def try_expand(line): @@ -331,13 +331,13 @@ class KconfigParser: arch = '' cpu = '' for line in read_file(self.dotconfig): - m = self.re_arch.match(line) - if m: - arch = m.group(1) + m_arch = self.re_arch.match(line) + if m_arch: + arch = m_arch.group(1) continue - m = self.re_cpu.match(line) - if m: - cpu = m.group(1) + m_cpu = self.re_cpu.match(line) + if m_cpu: + cpu = m_cpu.group(1) if not arch: return None @@ -422,7 +422,7 @@ class Slot: If the subprocess is still running, wait until it finishes. """ if self.state != STATE_IDLE: - while self.ps.poll() == None: + while self.proc.poll() == None: pass shutil.rmtree(self.build_dir) @@ -467,10 +467,10 @@ class Slot: if self.state == STATE_IDLE: return True - if self.ps.poll() == None: + if self.proc.poll() == None: return False - if self.ps.poll() != 0: + if self.proc.poll() != 0: self.handle_error() elif self.state == STATE_DEFCONFIG: if self.reference_src_dir and not self.current_src_dir: @@ -499,7 +499,7 @@ class Slot: 'Failed to process.\n') if self.args.verbose: self.log += color_text(self.args.color, COLOR_LIGHT_CYAN, - self.ps.stderr.read().decode()) + self.proc.stderr.read().decode()) self.finish(False) def do_defconfig(self): @@ -507,9 +507,9 @@ class Slot: cmd = list(self.make_cmd) cmd.append(self.defconfig) - self.ps = subprocess.Popen(cmd, stdout=self.devnull, - stderr=subprocess.PIPE, - cwd=self.current_src_dir) + self.proc = subprocess.Popen(cmd, stdout=self.devnull, + stderr=subprocess.PIPE, + cwd=self.current_src_dir) self.state = STATE_DEFCONFIG def do_autoconf(self): @@ -528,9 +528,9 @@ class Slot: cmd = list(self.make_cmd) cmd.append('KCONFIG_IGNORE_DUPLICATES=1') cmd.append(AUTO_CONF_PATH) - self.ps = subprocess.Popen(cmd, stdout=self.devnull, env=env, - stderr=subprocess.PIPE, - cwd=self.current_src_dir) + self.proc = subprocess.Popen(cmd, stdout=self.devnull, env=env, + stderr=subprocess.PIPE, + cwd=self.current_src_dir) self.state = STATE_AUTOCONF def do_build_db(self): @@ -552,8 +552,8 @@ class Slot: cmd = list(self.make_cmd) cmd.append('savedefconfig') - self.ps = subprocess.Popen(cmd, stdout=self.devnull, - stderr=subprocess.PIPE) + self.proc = subprocess.Popen(cmd, stdout=self.devnull, + stderr=subprocess.PIPE) self.state = STATE_SAVEDEFCONFIG def update_defconfig(self): @@ -1145,13 +1145,13 @@ def prefix_config(cfg): >>> prefix_config('A123') 'CONFIG_A123' """ - op = '' + oper = '' if cfg[0] == '~': - op = cfg[0] + oper = cfg[0] cfg = cfg[1:] if not cfg.startswith('CONFIG_'): cfg = 'CONFIG_' + cfg - return op + cfg + return oper + cfg RE_MK_CONFIGS = re.compile(r'CONFIG_(\$\(SPL_(?:TPL_)?\))?([A-Za-z0-9_]*)') @@ -1199,12 +1199,12 @@ def scan_makefiles(fnames): fname_uses = {} for fname, rest in fnames: m_iter = RE_MK_CONFIGS.finditer(rest) - for m in m_iter: - real_opt = m.group(2) + for mat in m_iter: + real_opt = mat.group(2) if real_opt == '': continue is_spl = False - if m.group(1): + if mat.group(1): is_spl = True use = ConfigUse(real_opt, is_spl, fname, rest) if fname not in fname_uses: @@ -1244,8 +1244,8 @@ def scan_src_files(fnames): rest = None def add_uses(m_iter, is_spl): - for m in m_iter: - real_opt = m.group(1) + for mat in m_iter: + real_opt = mat.group(1) if real_opt == '': continue use = ConfigUse(real_opt, is_spl, fname, rest) @@ -1573,9 +1573,9 @@ doc/develop/moveconfig.rst for documentation.''' # We are either building the database or forcing a sync of defconfigs config_db = {} db_queue = queue.Queue() - t = DatabaseThread(config_db, db_queue) - t.daemon = True - t.start() + dbt = DatabaseThread(config_db, db_queue) + dbt.daemon = True + dbt.start() check_clean_directory() bsettings.setup('') @@ -1598,12 +1598,12 @@ doc/develop/moveconfig.rst for documentation.''' subprocess.call(['git', 'commit', '-s', '-m', msg]) if args.build_db: - with open(CONFIG_DATABASE, 'w', encoding='utf-8') as fd: + with open(CONFIG_DATABASE, 'w', encoding='utf-8') as outf: for defconfig, configs in config_db.items(): - fd.write(f'{defconfig}\n') + outf.write(f'{defconfig}\n') for config in sorted(configs.keys()): - fd.write(f' {config}={configs[config]}\n') - fd.write('\n') + outf.write(f' {config}={configs[config]}\n') + outf.write('\n') if __name__ == '__main__': sys.exit(main()) -- cgit v1.1 From a6ab4dbd6063b18d4af64b65cfd57c218ed9f9db Mon Sep 17 00:00:00 2001 From: Simon Glass Date: Sat, 23 Sep 2023 13:44:02 -0600 Subject: moveconfig: Correct use of members not declared in __init__() Fix these pylint warnings. Signed-off-by: Simon Glass --- tools/moveconfig.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/tools/moveconfig.py b/tools/moveconfig.py index 2234f28..1dff891 100755 --- a/tools/moveconfig.py +++ b/tools/moveconfig.py @@ -410,6 +410,10 @@ class Slot: self.parser = KconfigParser(args, self.build_dir) self.state = STATE_IDLE self.failed_boards = set() + self.defconfig = None + self.log = '' + self.current_src_dir = None + self.proc = None def __del__(self): """Delete the working directory -- cgit v1.1 From b774ba52c6c3c9b255a18d2fa27ac9165946b7e6 Mon Sep 17 00:00:00 2001 From: Simon Glass Date: Sat, 23 Sep 2023 13:44:03 -0600 Subject: moveconfig: Correct list-comprehension warnings Correct some pylint warnings about needing to use list comprehension. Signed-off-by: Simon Glass --- tools/moveconfig.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/tools/moveconfig.py b/tools/moveconfig.py index 1dff891..d46433c 100755 --- a/tools/moveconfig.py +++ b/tools/moveconfig.py @@ -1422,12 +1422,12 @@ def do_scan_source(path, do_update): print('\nCONFIG options present in Makefiles but not Kconfig (SPL):') not_found = check_not_found(all_uses, MODE_SPL) show_uses(not_found) - spl_not_found |= set([is_not_proper(key) or key for key in not_found.keys()]) + spl_not_found |= {is_not_proper(key) or key for key in not_found.keys()} print('\nCONFIG options used as Proper in Makefiles but without a non-SPL_ variant:') not_found = check_not_found(all_uses, MODE_PROPER) show_uses(not_found) - proper_not_found |= set([key for key in not_found.keys()]) + proper_not_found |= {not_found.keys()} # Scan the source code all_uses, _ = scan_src_files(src_list) @@ -1440,12 +1440,12 @@ def do_scan_source(path, do_update): print('\nCONFIG options present in source but not Kconfig (SPL):') not_found = check_not_found(all_uses, MODE_SPL) show_uses(not_found) - spl_not_found |= set([is_not_proper(key) or key for key in not_found.keys()]) + spl_not_found |= {is_not_proper(key) or key for key in not_found.keys()} print('\nCONFIG options used as Proper in source but without a non-SPL_ variant:') not_found = check_not_found(all_uses, MODE_PROPER) show_uses(not_found) - proper_not_found |= set([key for key in not_found.keys()]) + proper_not_found |= {not_found.keys()} print('\nCONFIG options used as SPL but without an SPL_ variant:') for item in sorted(spl_not_found): -- cgit v1.1 From e6c686f40501bd287bf0199a88ab280ccd54b322 Mon Sep 17 00:00:00 2001 From: Simon Glass Date: Sat, 23 Sep 2023 13:44:04 -0600 Subject: moveconfig: Use an encoding with open() Fix pylint warnings about needing an explicit character encoding. Signed-off-by: Simon Glass --- tools/moveconfig.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/tools/moveconfig.py b/tools/moveconfig.py index d46433c..9b71659 100755 --- a/tools/moveconfig.py +++ b/tools/moveconfig.py @@ -1457,12 +1457,14 @@ def do_scan_source(path, do_update): # Write out the updated information if do_update: - with open(os.path.join(path, 'scripts', 'conf_nospl'), 'w') as out: + with open(os.path.join(path, 'scripts', 'conf_nospl'), 'w', + encoding='utf-8') as out: print('# These options should not be enabled in SPL builds\n', file=out) for item in sorted(spl_not_found): print(item, file=out) - with open(os.path.join(path, 'scripts', 'conf_noproper'), 'w') as out: + with open(os.path.join(path, 'scripts', 'conf_noproper'), 'w', + encoding='utf-8') as out: print('# These options should not be enabled in Proper builds\n', file=out) for item in sorted(proper_not_found): -- cgit v1.1 From f297ba33e99324b30355a5e935717936fe527927 Mon Sep 17 00:00:00 2001 From: Simon Glass Date: Sat, 23 Sep 2023 13:44:05 -0600 Subject: moveconfig: Fix misc pylint warnings Fix various remaining pylint warnings. Signed-off-by: Simon Glass --- tools/moveconfig.py | 23 ++++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/tools/moveconfig.py b/tools/moveconfig.py index 9b71659..727a5d6 100755 --- a/tools/moveconfig.py +++ b/tools/moveconfig.py @@ -233,8 +233,7 @@ def read_file(fname, as_lines=True, skip_unicode=False): try: if as_lines: return [line.rstrip('\n') for line in inf.readlines()] - else: - return inf.read() + return inf.read() except UnicodeDecodeError as exc: if not skip_unicode: raise @@ -426,7 +425,7 @@ class Slot: If the subprocess is still running, wait until it finishes. """ if self.state != STATE_IDLE: - while self.proc.poll() == None: + while self.proc.poll() is None: pass shutil.rmtree(self.build_dir) @@ -471,7 +470,7 @@ class Slot: if self.state == STATE_IDLE: return True - if self.proc.poll() == None: + if self.proc.poll() is None: return False if self.proc.poll() != 0: @@ -494,7 +493,7 @@ class Slot: else: sys.exit('Internal Error. This should not happen.') - return True if self.state == STATE_IDLE else False + return self.state == STATE_IDLE def handle_error(self): """Handle error cases.""" @@ -521,13 +520,13 @@ class Slot: arch = self.parser.get_arch() try: - toolchain = self.toolchains.Select(arch) + tchain = self.toolchains.Select(arch) except ValueError: self.log += color_text(self.args.color, COLOR_YELLOW, f"Tool chain for '{arch}' is missing. Do nothing.\n") self.finish(False) return - env = toolchain.MakeEnvironment(False) + env = tchain.MakeEnvironment(False) cmd = list(self.make_cmd) cmd.append('KCONFIG_IGNORE_DUPLICATES=1') @@ -1004,7 +1003,7 @@ def do_imply_config(config_list, add_imply, imply_flags, skip_added, # skip imply_config because prev is a superset skip = True break - elif count > prev_count: + if count > prev_count: # delete prev because imply_config is a superset del imply_configs[prev] if not skip: @@ -1540,7 +1539,7 @@ doc/develop/moveconfig.rst for documentation.''' if args.scan_source: do_scan_source(os.getcwd(), args.update) - return + return 0 if not any((args.force_sync, args.build_db, args.imply, args.find)): parser.print_usage() @@ -1570,11 +1569,11 @@ doc/develop/moveconfig.rst for documentation.''' imply_flags |= IMPLY_FLAGS[flag][0] do_imply_config(configs, args.add_imply, imply_flags, args.skip_added) - return + return 0 if args.find: do_find_config(configs) - return + return 0 # We are either building the database or forcing a sync of defconfigs config_db = {} @@ -1610,6 +1609,8 @@ doc/develop/moveconfig.rst for documentation.''' for config in sorted(configs.keys()): outf.write(f' {config}={configs[config]}\n') outf.write('\n') + return 0 + if __name__ == '__main__': sys.exit(main()) -- cgit v1.1 From 5aba58cf3bc4c1a094416b1ed5f2e5e9790b6f61 Mon Sep 17 00:00:00 2001 From: Simon Glass Date: Sat, 23 Sep 2023 13:44:06 -0600 Subject: moveconfig: Only show output when there is a reason There is no point in listing a board if everything went well. It makes it harder to see the failures, particularly on a fast machine. Suppress output unless something actually happened. Drop the 'Syncing by savedefconfig' since this is selected by the -s and is the same for all boards in this mode. Signed-off-by: Simon Glass --- tools/moveconfig.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/tools/moveconfig.py b/tools/moveconfig.py index 727a5d6..568386f 100755 --- a/tools/moveconfig.py +++ b/tools/moveconfig.py @@ -551,7 +551,6 @@ class Slot: if not self.args.force_sync: self.finish(True) return - self.log += 'Syncing by savedefconfig (forced by option)...\n' cmd = list(self.make_cmd) cmd.append('savedefconfig') @@ -581,12 +580,13 @@ class Slot: successfully, or False when it fails. """ # output at least 30 characters to hide the "* defconfigs out of *". - log = self.defconfig.ljust(30) + '\n' + if self.log: + log = self.defconfig.ljust(30) + '\n' - log += '\n'.join([ ' ' + s for s in self.log.split('\n') ]) - # Some threads are running in parallel. - # Print log atomically to not mix up logs from different threads. - print(log, file=(sys.stdout if success else sys.stderr)) + log += '\n'.join([ ' ' + s for s in self.log.split('\n') ]) + # Some threads are running in parallel. + # Print log atomically to not mix up logs from different threads. + print(log, file=(sys.stdout if success else sys.stderr)) if not success: if self.args.exit_on_error: -- cgit v1.1 From 9461bf0d65acb1b758c94dd722b10d471b2c8675 Mon Sep 17 00:00:00 2001 From: Simon Glass Date: Sat, 23 Sep 2023 13:44:07 -0600 Subject: moveconfig: Reduce the amount of output Output a single line in the case where the defconfig only has one line of output. Show the name without the _defconfig suffix, since that is the same for all boards. Use a list for the log so it is easier to process at the end. Signed-off-by: Simon Glass --- tools/moveconfig.py | 29 +++++++++++++++++------------ 1 file changed, 17 insertions(+), 12 deletions(-) diff --git a/tools/moveconfig.py b/tools/moveconfig.py index 568386f..9d22872 100755 --- a/tools/moveconfig.py +++ b/tools/moveconfig.py @@ -410,7 +410,7 @@ class Slot: self.state = STATE_IDLE self.failed_boards = set() self.defconfig = None - self.log = '' + self.log = [] self.current_src_dir = None self.proc = None @@ -446,7 +446,7 @@ class Slot: return False self.defconfig = defconfig - self.log = '' + self.log = [] self.current_src_dir = self.reference_src_dir self.do_defconfig() return True @@ -498,11 +498,12 @@ class Slot: def handle_error(self): """Handle error cases.""" - self.log += color_text(self.args.color, COLOR_LIGHT_RED, - 'Failed to process.\n') + self.log.append(color_text(self.args.color, COLOR_LIGHT_RED, + 'Failed to process')) if self.args.verbose: - self.log += color_text(self.args.color, COLOR_LIGHT_CYAN, - self.proc.stderr.read().decode()) + for line in self.proc.stderr.read().decode().splitlines(): + self.log.append(color_text(self.args.color, COLOR_LIGHT_CYAN, + line)) self.finish(False) def do_defconfig(self): @@ -522,8 +523,8 @@ class Slot: try: tchain = self.toolchains.Select(arch) except ValueError: - self.log += color_text(self.args.color, COLOR_YELLOW, - f"Tool chain for '{arch}' is missing. Do nothing.\n") + self.log.append(color_text(self.args.color, COLOR_YELLOW, + f"Tool chain for '{arch}' is missing: do nothing")) self.finish(False) return env = tchain.MakeEnvironment(False) @@ -565,8 +566,8 @@ class Slot: updated = not filecmp.cmp(orig_defconfig, new_defconfig) if updated: - self.log += color_text(self.args.color, COLOR_LIGHT_BLUE, - 'defconfig was updated.\n') + self.log.append(color_text(self.args.color, COLOR_LIGHT_BLUE, + 'defconfig updated')) if not self.args.dry_run and updated: shutil.move(new_defconfig, orig_defconfig) @@ -581,9 +582,13 @@ class Slot: """ # output at least 30 characters to hide the "* defconfigs out of *". if self.log: - log = self.defconfig.ljust(30) + '\n' + name = self.defconfig[:-len('_defconfig')] - log += '\n'.join([ ' ' + s for s in self.log.split('\n') ]) + # Put the first log line on the first line + log = name.ljust(20) + ' ' + self.log[0] + + if len(self.log) > 1: + log += '\n' + '\n'.join([' ' + s for s in self.log[1:]]) # Some threads are running in parallel. # Print log atomically to not mix up logs from different threads. print(log, file=(sys.stdout if success else sys.stderr)) -- cgit v1.1 From 95f0914ee807a090e6861a1abf96fb14b65af2f6 Mon Sep 17 00:00:00 2001 From: Simon Glass Date: Sat, 23 Sep 2023 13:44:08 -0600 Subject: moveconfig: Avoid showing progress at the end When the process is finished, moveconfig leaves a line saying that all boards were processed (for better or worse). Drop this, since it is unncessary. Future work will provide a summary at the end instead. Signed-off-by: Simon Glass --- tools/moveconfig.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tools/moveconfig.py b/tools/moveconfig.py index 9d22872..0131034 100755 --- a/tools/moveconfig.py +++ b/tools/moveconfig.py @@ -282,7 +282,8 @@ class Progress: def show(self): """Display the progress.""" - print(f' {self.current} defconfigs out of {self.total}\r', end=' ') + if self.current != self.total: + print(f' {self.current} defconfigs out of {self.total}\r', end=' ') sys.stdout.flush() -- cgit v1.1 From 15f19ab50188d426966e8232052189d4b263f9b9 Mon Sep 17 00:00:00 2001 From: Simon Glass Date: Sat, 23 Sep 2023 13:44:09 -0600 Subject: moveconfig: Use u_boot_pylib for terminal colour Use the existing terminal code to handle ANSI colours. Enable colour by default if the output is going to a terminal. Signed-off-by: Simon Glass --- tools/moveconfig.py | 92 ++++++++++++++++++++++------------------------------- 1 file changed, 38 insertions(+), 54 deletions(-) diff --git a/tools/moveconfig.py b/tools/moveconfig.py index 0131034..9e9cb67 100755 --- a/tools/moveconfig.py +++ b/tools/moveconfig.py @@ -33,6 +33,7 @@ import asteval from buildman import bsettings from buildman import kconfiglib from buildman import toolchain +from u_boot_pylib import terminal SHOW_GNU_MAKE = 'scripts/show-gnu-make' SLEEP_TIME=0.03 @@ -42,23 +43,6 @@ STATE_DEFCONFIG = 1 STATE_AUTOCONF = 2 STATE_SAVEDEFCONFIG = 3 -COLOR_BLACK = '0;30' -COLOR_RED = '0;31' -COLOR_GREEN = '0;32' -COLOR_BROWN = '0;33' -COLOR_BLUE = '0;34' -COLOR_PURPLE = '0;35' -COLOR_CYAN = '0;36' -COLOR_LIGHT_GRAY = '0;37' -COLOR_DARK_GRAY = '1;30' -COLOR_LIGHT_RED = '1;31' -COLOR_LIGHT_GREEN = '1;32' -COLOR_YELLOW = '1;33' -COLOR_LIGHT_BLUE = '1;34' -COLOR_LIGHT_PURPLE = '1;35' -COLOR_LIGHT_CYAN = '1;36' -COLOR_WHITE = '1;37' - AUTO_CONF_PATH = 'include/config/auto.conf' CONFIG_DATABASE = 'moveconfig.db' @@ -189,15 +173,6 @@ def get_all_defconfigs(): return defconfigs -def color_text(color_enabled, color, string): - """Return colored string.""" - if color_enabled: - # LF should not be surrounded by the escape sequence. - # Otherwise, additional whitespace or line-feed might be printed. - return '\n'.join([ '\033[' + color + 'm' + s + '\033[0m' if s else '' - for s in string.split('\n') ]) - return string - def write_file(fname, data): """Write data to a file @@ -385,8 +360,8 @@ class Slot: for faster processing. """ - def __init__(self, toolchains, args, progress, devnull, - make_cmd, reference_src_dir, db_queue): + def __init__(self, toolchains, args, progress, devnull, make_cmd, + reference_src_dir, db_queue, col): """Create a new process slot. Args: @@ -398,6 +373,7 @@ class Slot: reference_src_dir: Determine the true starting config state from this source tree. db_queue: output queue to write config info for the database + col (terminal.Color): Colour object """ self.toolchains = toolchains self.args = args @@ -407,6 +383,7 @@ class Slot: self.make_cmd = (make_cmd, 'O=' + self.build_dir) self.reference_src_dir = reference_src_dir self.db_queue = db_queue + self.col = col self.parser = KconfigParser(args, self.build_dir) self.state = STATE_IDLE self.failed_boards = set() @@ -499,12 +476,11 @@ class Slot: def handle_error(self): """Handle error cases.""" - self.log.append(color_text(self.args.color, COLOR_LIGHT_RED, - 'Failed to process')) + self.log.append(self.col.build(self.col.RED, 'Failed to process', + bright=True)) if self.args.verbose: for line in self.proc.stderr.read().decode().splitlines(): - self.log.append(color_text(self.args.color, COLOR_LIGHT_CYAN, - line)) + self.log.append(self.col.build(self.col.CYAN, line, True)) self.finish(False) def do_defconfig(self): @@ -524,8 +500,9 @@ class Slot: try: tchain = self.toolchains.Select(arch) except ValueError: - self.log.append(color_text(self.args.color, COLOR_YELLOW, - f"Tool chain for '{arch}' is missing: do nothing")) + self.log.append(self.col.build( + self.col.YELLOW, + f"Tool chain for '{arch}' is missing: do nothing")) self.finish(False) return env = tchain.MakeEnvironment(False) @@ -567,8 +544,8 @@ class Slot: updated = not filecmp.cmp(orig_defconfig, new_defconfig) if updated: - self.log.append(color_text(self.args.color, COLOR_LIGHT_BLUE, - 'defconfig updated')) + self.log.append( + self.col.build(self.col.BLUE, 'defconfig updated', bright=True)) if not self.args.dry_run and updated: shutil.move(new_defconfig, orig_defconfig) @@ -614,24 +591,27 @@ class Slots: """Controller of the array of subprocess slots.""" - def __init__(self, toolchains, args, progress, reference_src_dir, db_queue): + def __init__(self, toolchains, args, progress, reference_src_dir, db_queue, + col): """Create a new slots controller. Args: - toolchains: Toolchains object containing toolchains. - args: Program arguments - progress: A progress indicator. - reference_src_dir: Determine the true starting config state from this - source tree. - db_queue: output queue to write config info for the database + toolchains (Toolchains): Toolchains object containing toolchains + args (Namespace): Program arguments + progress (Progress): A progress indicator. + reference_src_dir (str): Determine the true starting config state + from this source tree (None for none) + db_queue (Queue): output queue to write config info for the database + col (terminal.Color): Colour object """ self.args = args self.slots = [] + self.col = col devnull = subprocess.DEVNULL make_cmd = get_make_cmd() for _ in range(args.jobs): self.slots.append(Slot(toolchains, args, progress, devnull, - make_cmd, reference_src_dir, db_queue)) + make_cmd, reference_src_dir, db_queue, col)) def add(self, defconfig): """Add a new subprocess if a vacant slot is found. @@ -683,8 +663,8 @@ class Slots: msg = 'The following boards were not processed due to error:\n' msg += boards msg += f'(the list has been saved in {output_file})\n' - print(color_text(self.args.color, COLOR_LIGHT_RED, - msg), file=sys.stderr) + print(self.col.build(self.col.RED, msg, bright=True), + file=sys.stderr) write_file(output_file, boards) @@ -723,13 +703,14 @@ class ReferenceSource: return self.src_dir -def move_config(toolchains, args, db_queue): +def move_config(toolchains, args, db_queue, col): """Build database or sync config options to defconfig files. Args: - toolchains (Toolchains): Toolchains to use - args (Namespace): Program arguments - db_queue (Queue): Queue for database updates + toolchains (Toolchains): Toolchains to use + args (Namespace): Program arguments + db_queue (Queue): Queue for database updates + col (terminal.Color): Colour object """ if args.force_sync: print('Syncing defconfigs', end=' ') @@ -749,7 +730,7 @@ def move_config(toolchains, args, db_queue): defconfigs = get_all_defconfigs() progress = Progress(len(defconfigs)) - slots = Slots(toolchains, args, progress, reference_src_dir, db_queue) + slots = Slots(toolchains, args, progress, reference_src_dir, db_queue, col) # Main loop to process defconfig files: # Add a new subprocess into a vacant slot. @@ -1495,10 +1476,10 @@ doc/develop/moveconfig.rst for documentation.''' 'implying others') parser.add_argument('-b', '--build-db', action='store_true', default=False, help='build a CONFIG database') - parser.add_argument('-c', '--color', action='store_true', default=False, - help='display the log in color') parser.add_argument('-C', '--commit', action='store_true', default=False, help='Create a git commit for the operation') + parser.add_argument('--nocolour', action='store_true', default=False, + help="don't display the log in colour") parser.add_argument('-d', '--defconfigs', type=str, help='a file containing a list of defconfigs to move, ' "one per line (for example 'snow_defconfig') " @@ -1543,6 +1524,9 @@ doc/develop/moveconfig.rst for documentation.''' return 1 unittest.main() + col = terminal.Color(terminal.COLOR_NEVER if args.nocolour + else terminal.COLOR_IF_TERMINAL) + if args.scan_source: do_scan_source(os.getcwd(), args.update) return 0 @@ -1593,7 +1577,7 @@ doc/develop/moveconfig.rst for documentation.''' toolchains = toolchain.Toolchains() toolchains.GetSettings() toolchains.Scan(verbose=False) - move_config(toolchains, args, db_queue) + move_config(toolchains, args, db_queue, col) db_queue.join() if args.commit: -- cgit v1.1 From 6b25d21c8657c4c72dacbec547f560eb8579199e Mon Sep 17 00:00:00 2001 From: Simon Glass Date: Sat, 23 Sep 2023 13:44:10 -0600 Subject: moveconfig: Show failures in progress Show the number of accumulated failures when processing. Use a shorter format with colour. An unwanted space appears before the defconfig name on every item except the last. Fix that while we are here. Signed-off-by: Simon Glass --- tools/moveconfig.py | 26 +++++++++++++++++++------- 1 file changed, 19 insertions(+), 7 deletions(-) diff --git a/tools/moveconfig.py b/tools/moveconfig.py index 9e9cb67..2a4badf 100755 --- a/tools/moveconfig.py +++ b/tools/moveconfig.py @@ -241,24 +241,36 @@ class Progress: """Progress Indicator""" - def __init__(self, total): + def __init__(self, col, total): """Create a new progress indicator. Args: - total: A number of defconfig files to process. + color_enabled (bool): True for colour output + total (int): A number of defconfig files to process. """ + self.col = col self.current = 0 + self.good = 0 self.total = total - def inc(self): - """Increment the number of processed defconfig files.""" + def inc(self, success): + """Increment the number of processed defconfig files. + Args: + success (bool): True if processing succeeded + """ + self.good += success self.current += 1 def show(self): """Display the progress.""" if self.current != self.total: - print(f' {self.current} defconfigs out of {self.total}\r', end=' ') + line = self.col.build(self.col.GREEN, f'{self.good:5d}') + line += self.col.build(self.col.RED, + f'{self.current - self.good:5d}') + line += self.col.build(self.col.MAGENTA, + f'/{self.total - self.current}') + print(f'{line} \r', end='') sys.stdout.flush() @@ -578,7 +590,7 @@ class Slot: # Record the failed board. self.failed_boards.add(self.defconfig) - self.progress.inc() + self.progress.inc(success) self.progress.show() self.state = STATE_IDLE @@ -729,7 +741,7 @@ def move_config(toolchains, args, db_queue, col): else: defconfigs = get_all_defconfigs() - progress = Progress(len(defconfigs)) + progress = Progress(col, len(defconfigs)) slots = Slots(toolchains, args, progress, reference_src_dir, db_queue, col) # Main loop to process defconfig files: -- cgit v1.1 From dc1d2e6c7f932386a3ef2d40de65c6659d928bb2 Mon Sep 17 00:00:00 2001 From: Simon Glass Date: Sat, 23 Sep 2023 13:44:11 -0600 Subject: moveconfig: Show a summary at the end Rather than printing all the failed boards, which are now easily visible on the terminal, just show a summary. Sort it by defconfig and drop the '_defconfig' suffix. Signed-off-by: Simon Glass --- tools/moveconfig.py | 28 +++++++++++++++------------- 1 file changed, 15 insertions(+), 13 deletions(-) diff --git a/tools/moveconfig.py b/tools/moveconfig.py index 2a4badf..c6d7c53 100755 --- a/tools/moveconfig.py +++ b/tools/moveconfig.py @@ -571,8 +571,8 @@ class Slot: successfully, or False when it fails. """ # output at least 30 characters to hide the "* defconfigs out of *". + name = self.defconfig[:-len('_defconfig')] if self.log: - name = self.defconfig[:-len('_defconfig')] # Put the first log line on the first line log = name.ljust(20) + ' ' + self.log[0] @@ -588,7 +588,7 @@ class Slot: sys.exit('Exit on error.') # If --exit-on-error flag is not set, skip this board and continue. # Record the failed board. - self.failed_boards.add(self.defconfig) + self.failed_boards.add(name) self.progress.inc(success) self.progress.show() @@ -618,6 +618,7 @@ class Slots: """ self.args = args self.slots = [] + self.progress = progress self.col = col devnull = subprocess.DEVNULL make_cmd = get_make_cmd() @@ -662,8 +663,8 @@ class Slots: ret = False return ret - def show_failed_boards(self): - """Display all of the failed boards (defconfigs).""" + def show_result(self): + """Show the results of processing""" boards = set() output_file = 'moveconfig.failed' @@ -671,14 +672,16 @@ class Slots: boards |= slot.get_failed_boards() if boards: - boards = '\n'.join(boards) + '\n' - msg = 'The following boards were not processed due to error:\n' - msg += boards - msg += f'(the list has been saved in {output_file})\n' - print(self.col.build(self.col.RED, msg, bright=True), - file=sys.stderr) - + print(self.col.build( + self.col.RED, + f'{len(boards)} failed (see {output_file})', True)) + boards = '\n'.join(sorted(boards)) + '\n' write_file(output_file, boards) + else: + # Add enough spaces to overwrite the progress indicator + print(self.col.build( + self.col.GREEN, + f'{self.progress.total} processed ', bright=True)) class ReferenceSource: @@ -757,8 +760,7 @@ def move_config(toolchains, args, db_queue, col): while not slots.empty(): time.sleep(SLEEP_TIME) - print('') - slots.show_failed_boards() + slots.show_result() def find_kconfig_rules(kconf, config, imply_config): """Check whether a config has a 'select' or 'imply' keyword -- cgit v1.1 From fc07d99e6a3a15dc4a6e75134efad1e4b90a4339 Mon Sep 17 00:00:00 2001 From: Simon Glass Date: Sat, 23 Sep 2023 13:44:12 -0600 Subject: moveconfig: Drop the initial output Since moveconfig now just does what it is told (build database or sync defconfigs) we don't need to print what it is doing. Drop this info, which is of very little use. Signed-off-by: Simon Glass --- tools/moveconfig.py | 6 ------ 1 file changed, 6 deletions(-) diff --git a/tools/moveconfig.py b/tools/moveconfig.py index c6d7c53..5392e1f 100755 --- a/tools/moveconfig.py +++ b/tools/moveconfig.py @@ -727,12 +727,6 @@ def move_config(toolchains, args, db_queue, col): db_queue (Queue): Queue for database updates col (terminal.Color): Colour object """ - if args.force_sync: - print('Syncing defconfigs', end=' ') - elif args.build_db: - print(f'Building {CONFIG_DATABASE} database') - print(f'(jobs: {args.jobs})\n') - if args.git_ref: reference_src = ReferenceSource(args.git_ref) reference_src_dir = reference_src.get_dir() -- cgit v1.1 From 94e2ed7c8e9d253c25222d42607425944cfe167f Mon Sep 17 00:00:00 2001 From: Simon Glass Date: Sat, 23 Sep 2023 13:44:13 -0600 Subject: moveconfig: Move summaries to the end Write the summary for -s and -b at the end, using a unified format. Signed-off-by: Simon Glass --- tools/moveconfig.py | 36 +++++++++++++++++++++++------------- 1 file changed, 23 insertions(+), 13 deletions(-) diff --git a/tools/moveconfig.py b/tools/moveconfig.py index 5392e1f..ed75d32 100755 --- a/tools/moveconfig.py +++ b/tools/moveconfig.py @@ -45,6 +45,7 @@ STATE_SAVEDEFCONFIG = 3 AUTO_CONF_PATH = 'include/config/auto.conf' CONFIG_DATABASE = 'moveconfig.db' +FAILED_LIST = 'moveconfig.failed' CONFIG_LEN = len('CONFIG_') @@ -663,25 +664,17 @@ class Slots: ret = False return ret - def show_result(self): + def write_failed_boards(self): """Show the results of processing""" boards = set() - output_file = 'moveconfig.failed' for slot in self.slots: boards |= slot.get_failed_boards() if boards: - print(self.col.build( - self.col.RED, - f'{len(boards)} failed (see {output_file})', True)) boards = '\n'.join(sorted(boards)) + '\n' - write_file(output_file, boards) - else: - # Add enough spaces to overwrite the progress indicator - print(self.col.build( - self.col.GREEN, - f'{self.progress.total} processed ', bright=True)) + write_file(FAILED_LIST, boards) + class ReferenceSource: @@ -726,6 +719,9 @@ def move_config(toolchains, args, db_queue, col): args (Namespace): Program arguments db_queue (Queue): Queue for database updates col (terminal.Color): Colour object + + Returns: + Progress: Progress indicator """ if args.git_ref: reference_src = ReferenceSource(args.git_ref) @@ -754,7 +750,8 @@ def move_config(toolchains, args, db_queue, col): while not slots.empty(): time.sleep(SLEEP_TIME) - slots.show_result() + slots.write_failed_boards() + return progress def find_kconfig_rules(kconf, config, imply_config): """Check whether a config has a 'select' or 'imply' keyword @@ -1585,7 +1582,7 @@ doc/develop/moveconfig.rst for documentation.''' toolchains = toolchain.Toolchains() toolchains.GetSettings() toolchains.Scan(verbose=False) - move_config(toolchains, args, db_queue, col) + progress = move_config(toolchains, args, db_queue, col) db_queue.join() if args.commit: @@ -1600,6 +1597,8 @@ doc/develop/moveconfig.rst for documentation.''' msg += '\n\nRsync all defconfig files using moveconfig.py' subprocess.call(['git', 'commit', '-s', '-m', msg]) + failed = progress.total - progress.good + failure = f'{failed} failed, ' if failed else '' if args.build_db: with open(CONFIG_DATABASE, 'w', encoding='utf-8') as outf: for defconfig, configs in config_db.items(): @@ -1607,6 +1606,17 @@ doc/develop/moveconfig.rst for documentation.''' for config in sorted(configs.keys()): outf.write(f' {config}={configs[config]}\n') outf.write('\n') + print(col.build( + col.RED if failed else col.GREEN, + f'{failure}{len(config_db)} boards written to {CONFIG_DATABASE}')) + else: + if failed: + print(col.build(col.RED, f'{failure}see {FAILED_LIST}', True)) + else: + # Add enough spaces to overwrite the progress indicator + print(col.build( + col.GREEN, f'{progress.total} processed ', bright=True)) + return 0 -- cgit v1.1 From ea4d6dead3728e5e7e6a2f070ca240de832bce92 Mon Sep 17 00:00:00 2001 From: Simon Glass Date: Sat, 23 Sep 2023 13:44:14 -0600 Subject: moveconfig: Rename the tool to qconfig This does not move configs anymore, but queries them, based on a database it can build. Rename the tool to better reflect its purpose. Signed-off-by: Simon Glass --- tools/moveconfig.py | 1624 --------------------------------------------------- tools/qconfig.py | 1624 +++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 1624 insertions(+), 1624 deletions(-) delete mode 100755 tools/moveconfig.py create mode 100755 tools/qconfig.py diff --git a/tools/moveconfig.py b/tools/moveconfig.py deleted file mode 100755 index ed75d32..0000000 --- a/tools/moveconfig.py +++ /dev/null @@ -1,1624 +0,0 @@ -#!/usr/bin/env python3 -# SPDX-License-Identifier: GPL-2.0+ -# -# Author: Masahiro Yamada -# - -""" -Move config options from headers to defconfig files. - -See doc/develop/moveconfig.rst for documentation. -""" - -from argparse import ArgumentParser -import collections -from contextlib import ExitStack -import doctest -import filecmp -import fnmatch -import glob -import multiprocessing -import os -import queue -import re -import shutil -import subprocess -import sys -import tempfile -import threading -import time -import unittest - -import asteval -from buildman import bsettings -from buildman import kconfiglib -from buildman import toolchain -from u_boot_pylib import terminal - -SHOW_GNU_MAKE = 'scripts/show-gnu-make' -SLEEP_TIME=0.03 - -STATE_IDLE = 0 -STATE_DEFCONFIG = 1 -STATE_AUTOCONF = 2 -STATE_SAVEDEFCONFIG = 3 - -AUTO_CONF_PATH = 'include/config/auto.conf' -CONFIG_DATABASE = 'moveconfig.db' -FAILED_LIST = 'moveconfig.failed' - -CONFIG_LEN = len('CONFIG_') - -SIZES = { - 'SZ_1': 0x00000001, 'SZ_2': 0x00000002, - 'SZ_4': 0x00000004, 'SZ_8': 0x00000008, - 'SZ_16': 0x00000010, 'SZ_32': 0x00000020, - 'SZ_64': 0x00000040, 'SZ_128': 0x00000080, - 'SZ_256': 0x00000100, 'SZ_512': 0x00000200, - 'SZ_1K': 0x00000400, 'SZ_2K': 0x00000800, - 'SZ_4K': 0x00001000, 'SZ_8K': 0x00002000, - 'SZ_16K': 0x00004000, 'SZ_32K': 0x00008000, - 'SZ_64K': 0x00010000, 'SZ_128K': 0x00020000, - 'SZ_256K': 0x00040000, 'SZ_512K': 0x00080000, - 'SZ_1M': 0x00100000, 'SZ_2M': 0x00200000, - 'SZ_4M': 0x00400000, 'SZ_8M': 0x00800000, - 'SZ_16M': 0x01000000, 'SZ_32M': 0x02000000, - 'SZ_64M': 0x04000000, 'SZ_128M': 0x08000000, - 'SZ_256M': 0x10000000, 'SZ_512M': 0x20000000, - 'SZ_1G': 0x40000000, 'SZ_2G': 0x80000000, - 'SZ_4G': 0x100000000 -} - -RE_REMOVE_DEFCONFIG = re.compile(r'(.*)_defconfig') - -# CONFIG symbols present in the build system (from Linux) but not actually used -# in U-Boot; KCONFIG symbols -IGNORE_SYMS = ['DEBUG_SECTION_MISMATCH', 'FTRACE_MCOUNT_RECORD', 'GCOV_KERNEL', - 'GCOV_PROFILE_ALL', 'KALLSYMS', 'KASAN', 'MODVERSIONS', 'SHELL', - 'TPL_BUILD', 'VPL_BUILD', 'IS_ENABLED', 'FOO', 'IF_ENABLED_INT', - 'IS_ENABLED_', 'IS_ENABLED_1', 'IS_ENABLED_2', 'IS_ENABLED_3', - 'SPL_', 'TPL_', 'SPL_FOO', 'TPL_FOO', 'TOOLS_FOO', - 'ACME', 'SPL_ACME', 'TPL_ACME', 'TRACE_BRANCH_PROFILING', - 'VAL', '_UNDEFINED', 'SPL_BUILD', ] - -SPL_PREFIXES = ['SPL_', 'TPL_', 'VPL_', 'TOOLS_'] - -### helper functions ### -def check_top_directory(): - """Exit if we are not at the top of source directory.""" - for fname in 'README', 'Licenses': - if not os.path.exists(fname): - sys.exit('Please run at the top of source directory.') - -def check_clean_directory(): - """Exit if the source tree is not clean.""" - for fname in '.config', 'include/config': - if os.path.exists(fname): - sys.exit("source tree is not clean, please run 'make mrproper'") - -def get_make_cmd(): - """Get the command name of GNU Make. - - U-Boot needs GNU Make for building, but the command name is not - necessarily "make". (for example, "gmake" on FreeBSD). - Returns the most appropriate command name on your system. - """ - with subprocess.Popen([SHOW_GNU_MAKE], stdout=subprocess.PIPE) as proc: - ret = proc.communicate() - if proc.returncode: - sys.exit('GNU Make not found') - return ret[0].rstrip() - -def get_matched_defconfig(line): - """Get the defconfig files that match a pattern - - Args: - line (str): Path or filename to match, e.g. 'configs/snow_defconfig' or - 'k2*_defconfig'. If no directory is provided, 'configs/' is - prepended - - Returns: - list of str: a list of matching defconfig files - """ - dirname = os.path.dirname(line) - if dirname: - pattern = line - else: - pattern = os.path.join('configs', line) - return glob.glob(pattern) + glob.glob(pattern + '_defconfig') - -def get_matched_defconfigs(defconfigs_file): - """Get all the defconfig files that match the patterns in a file. - - Args: - defconfigs_file (str): File containing a list of defconfigs to process, - or '-' to read the list from stdin - - Returns: - list of str: A list of paths to defconfig files, with no duplicates - """ - defconfigs = [] - with ExitStack() as stack: - if defconfigs_file == '-': - inf = sys.stdin - defconfigs_file = 'stdin' - else: - inf = stack.enter_context(open(defconfigs_file, encoding='utf-8')) - for i, line in enumerate(inf): - line = line.strip() - if not line: - continue # skip blank lines silently - if ' ' in line: - line = line.split(' ')[0] # handle 'git log' input - matched = get_matched_defconfig(line) - if not matched: - print(f"warning: {defconfigs_file}:{i + 1}: no defconfig matched '{line}'", - file=sys.stderr) - - defconfigs += matched - - # use set() to drop multiple matching - return [defconfig[len('configs') + 1:] for defconfig in set(defconfigs)] - -def get_all_defconfigs(): - """Get all the defconfig files under the configs/ directory. - - Returns: - list of str: List of paths to defconfig files - """ - defconfigs = [] - for (dirpath, _, filenames) in os.walk('configs'): - dirpath = dirpath[len('configs') + 1:] - for filename in fnmatch.filter(filenames, '*_defconfig'): - defconfigs.append(os.path.join(dirpath, filename)) - - return defconfigs - -def write_file(fname, data): - """Write data to a file - - Args: - fname (str): Filename to write to - data (list of str): Lines to write (with or without trailing newline); - or str to write - """ - with open(fname, 'w', encoding='utf-8') as out: - if isinstance(data, list): - for line in data: - print(line.rstrip('\n'), file=out) - else: - out.write(data) - -def read_file(fname, as_lines=True, skip_unicode=False): - """Read a file and return the contents - - Args: - fname (str): Filename to read from - as_lines (bool): Return file contents as a list of lines - skip_unicode (bool): True to report unicode errors and continue - - Returns: - iter of str: List of ;ines from the file with newline removed; str if - as_lines is False with newlines intact; or None if a unicode error - occurred - - Raises: - UnicodeDecodeError: Unicode error occurred when reading - """ - with open(fname, encoding='utf-8') as inf: - try: - if as_lines: - return [line.rstrip('\n') for line in inf.readlines()] - return inf.read() - except UnicodeDecodeError as exc: - if not skip_unicode: - raise - print(f"Failed on file '{fname}: {exc}") - return None - -def try_expand(line): - """If value looks like an expression, try expanding it - Otherwise just return the existing value - """ - if line.find('=') == -1: - return line - - try: - aeval = asteval.Interpreter( usersyms=SIZES, minimal=True ) - cfg, val = re.split("=", line) - val= val.strip('\"') - if re.search(r'[*+-/]|<<|SZ_+|\(([^\)]+)\)', val): - newval = hex(aeval(val)) - print(f'\tExpanded expression {val} to {newval}') - return cfg+'='+newval - except: - print(f'\tFailed to expand expression in {line}') - - return line - - -### classes ### -class Progress: - - """Progress Indicator""" - - def __init__(self, col, total): - """Create a new progress indicator. - - Args: - color_enabled (bool): True for colour output - total (int): A number of defconfig files to process. - """ - self.col = col - self.current = 0 - self.good = 0 - self.total = total - - def inc(self, success): - """Increment the number of processed defconfig files. - - Args: - success (bool): True if processing succeeded - """ - self.good += success - self.current += 1 - - def show(self): - """Display the progress.""" - if self.current != self.total: - line = self.col.build(self.col.GREEN, f'{self.good:5d}') - line += self.col.build(self.col.RED, - f'{self.current - self.good:5d}') - line += self.col.build(self.col.MAGENTA, - f'/{self.total - self.current}') - print(f'{line} \r', end='') - sys.stdout.flush() - - -class KconfigScanner: - """Kconfig scanner.""" - - def __init__(self): - """Scan all the Kconfig files and create a Config object.""" - # Define environment variables referenced from Kconfig - os.environ['srctree'] = os.getcwd() - os.environ['UBOOTVERSION'] = 'dummy' - os.environ['KCONFIG_OBJDIR'] = '' - os.environ['CC'] = 'gcc' - self.conf = kconfiglib.Kconfig() - - -class KconfigParser: - - """A parser of .config and include/autoconf.mk.""" - - re_arch = re.compile(r'CONFIG_SYS_ARCH="(.*)"') - re_cpu = re.compile(r'CONFIG_SYS_CPU="(.*)"') - - def __init__(self, args, build_dir): - """Create a new parser. - - Args: - args (Namespace): program arguments - build_dir: Build directory. - """ - self.args = args - self.dotconfig = os.path.join(build_dir, '.config') - self.autoconf = os.path.join(build_dir, 'include', 'autoconf.mk') - self.spl_autoconf = os.path.join(build_dir, 'spl', 'include', - 'autoconf.mk') - self.config_autoconf = os.path.join(build_dir, AUTO_CONF_PATH) - self.defconfig = os.path.join(build_dir, 'defconfig') - - def get_arch(self): - """Parse .config file and return the architecture. - - Returns: - Architecture name (e.g. 'arm'). - """ - arch = '' - cpu = '' - for line in read_file(self.dotconfig): - m_arch = self.re_arch.match(line) - if m_arch: - arch = m_arch.group(1) - continue - m_cpu = self.re_cpu.match(line) - if m_cpu: - cpu = m_cpu.group(1) - - if not arch: - return None - - # fix-up for aarch64 - if arch == 'arm' and cpu == 'armv8': - arch = 'aarch64' - - return arch - - -class DatabaseThread(threading.Thread): - """This thread processes results from Slot threads. - - It collects the data in the master config directary. There is only one - result thread, and this helps to serialise the build output. - """ - def __init__(self, config_db, db_queue): - """Set up a new result thread - - Args: - builder: Builder which will be sent each result - """ - threading.Thread.__init__(self) - self.config_db = config_db - self.db_queue= db_queue - - def run(self): - """Called to start up the result thread. - - We collect the next result job and pass it on to the build. - """ - while True: - defconfig, configs = self.db_queue.get() - self.config_db[defconfig] = configs - self.db_queue.task_done() - - -class Slot: - - """A slot to store a subprocess. - - Each instance of this class handles one subprocess. - This class is useful to control multiple threads - for faster processing. - """ - - def __init__(self, toolchains, args, progress, devnull, make_cmd, - reference_src_dir, db_queue, col): - """Create a new process slot. - - Args: - toolchains: Toolchains object containing toolchains. - args: Program arguments - progress: A progress indicator. - devnull: A file object of '/dev/null'. - make_cmd: command name of GNU Make. - reference_src_dir: Determine the true starting config state from this - source tree. - db_queue: output queue to write config info for the database - col (terminal.Color): Colour object - """ - self.toolchains = toolchains - self.args = args - self.progress = progress - self.build_dir = tempfile.mkdtemp() - self.devnull = devnull - self.make_cmd = (make_cmd, 'O=' + self.build_dir) - self.reference_src_dir = reference_src_dir - self.db_queue = db_queue - self.col = col - self.parser = KconfigParser(args, self.build_dir) - self.state = STATE_IDLE - self.failed_boards = set() - self.defconfig = None - self.log = [] - self.current_src_dir = None - self.proc = None - - def __del__(self): - """Delete the working directory - - This function makes sure the temporary directory is cleaned away - even if Python suddenly dies due to error. It should be done in here - because it is guaranteed the destructor is always invoked when the - instance of the class gets unreferenced. - - If the subprocess is still running, wait until it finishes. - """ - if self.state != STATE_IDLE: - while self.proc.poll() is None: - pass - shutil.rmtree(self.build_dir) - - def add(self, defconfig): - """Assign a new subprocess for defconfig and add it to the slot. - - If the slot is vacant, create a new subprocess for processing the - given defconfig and add it to the slot. Just returns False if - the slot is occupied (i.e. the current subprocess is still running). - - Args: - defconfig (str): defconfig name. - - Returns: - Return True on success or False on failure - """ - if self.state != STATE_IDLE: - return False - - self.defconfig = defconfig - self.log = [] - self.current_src_dir = self.reference_src_dir - self.do_defconfig() - return True - - def poll(self): - """Check the status of the subprocess and handle it as needed. - - Returns True if the slot is vacant (i.e. in idle state). - If the configuration is successfully finished, assign a new - subprocess to build include/autoconf.mk. - If include/autoconf.mk is generated, invoke the parser to - parse the .config and the include/autoconf.mk, moving - config options to the .config as needed. - If the .config was updated, run "make savedefconfig" to sync - it, update the original defconfig, and then set the slot back - to the idle state. - - Returns: - Return True if the subprocess is terminated, False otherwise - """ - if self.state == STATE_IDLE: - return True - - if self.proc.poll() is None: - return False - - if self.proc.poll() != 0: - self.handle_error() - elif self.state == STATE_DEFCONFIG: - if self.reference_src_dir and not self.current_src_dir: - self.do_savedefconfig() - else: - self.do_autoconf() - elif self.state == STATE_AUTOCONF: - if self.current_src_dir: - self.current_src_dir = None - self.do_defconfig() - elif self.args.build_db: - self.do_build_db() - else: - self.do_savedefconfig() - elif self.state == STATE_SAVEDEFCONFIG: - self.update_defconfig() - else: - sys.exit('Internal Error. This should not happen.') - - return self.state == STATE_IDLE - - def handle_error(self): - """Handle error cases.""" - - self.log.append(self.col.build(self.col.RED, 'Failed to process', - bright=True)) - if self.args.verbose: - for line in self.proc.stderr.read().decode().splitlines(): - self.log.append(self.col.build(self.col.CYAN, line, True)) - self.finish(False) - - def do_defconfig(self): - """Run 'make _defconfig' to create the .config file.""" - - cmd = list(self.make_cmd) - cmd.append(self.defconfig) - self.proc = subprocess.Popen(cmd, stdout=self.devnull, - stderr=subprocess.PIPE, - cwd=self.current_src_dir) - self.state = STATE_DEFCONFIG - - def do_autoconf(self): - """Run 'make AUTO_CONF_PATH'.""" - - arch = self.parser.get_arch() - try: - tchain = self.toolchains.Select(arch) - except ValueError: - self.log.append(self.col.build( - self.col.YELLOW, - f"Tool chain for '{arch}' is missing: do nothing")) - self.finish(False) - return - env = tchain.MakeEnvironment(False) - - cmd = list(self.make_cmd) - cmd.append('KCONFIG_IGNORE_DUPLICATES=1') - cmd.append(AUTO_CONF_PATH) - self.proc = subprocess.Popen(cmd, stdout=self.devnull, env=env, - stderr=subprocess.PIPE, - cwd=self.current_src_dir) - self.state = STATE_AUTOCONF - - def do_build_db(self): - """Add the board to the database""" - configs = {} - for line in read_file(os.path.join(self.build_dir, AUTO_CONF_PATH)): - if line.startswith('CONFIG'): - config, value = line.split('=', 1) - configs[config] = value.rstrip() - self.db_queue.put([self.defconfig, configs]) - self.finish(True) - - def do_savedefconfig(self): - """Update the .config and run 'make savedefconfig'.""" - if not self.args.force_sync: - self.finish(True) - return - - cmd = list(self.make_cmd) - cmd.append('savedefconfig') - self.proc = subprocess.Popen(cmd, stdout=self.devnull, - stderr=subprocess.PIPE) - self.state = STATE_SAVEDEFCONFIG - - def update_defconfig(self): - """Update the input defconfig and go back to the idle state.""" - orig_defconfig = os.path.join('configs', self.defconfig) - new_defconfig = os.path.join(self.build_dir, 'defconfig') - updated = not filecmp.cmp(orig_defconfig, new_defconfig) - - if updated: - self.log.append( - self.col.build(self.col.BLUE, 'defconfig updated', bright=True)) - - if not self.args.dry_run and updated: - shutil.move(new_defconfig, orig_defconfig) - self.finish(True) - - def finish(self, success): - """Display log along with progress and go to the idle state. - - Args: - success (bool): Should be True when the defconfig was processed - successfully, or False when it fails. - """ - # output at least 30 characters to hide the "* defconfigs out of *". - name = self.defconfig[:-len('_defconfig')] - if self.log: - - # Put the first log line on the first line - log = name.ljust(20) + ' ' + self.log[0] - - if len(self.log) > 1: - log += '\n' + '\n'.join([' ' + s for s in self.log[1:]]) - # Some threads are running in parallel. - # Print log atomically to not mix up logs from different threads. - print(log, file=(sys.stdout if success else sys.stderr)) - - if not success: - if self.args.exit_on_error: - sys.exit('Exit on error.') - # If --exit-on-error flag is not set, skip this board and continue. - # Record the failed board. - self.failed_boards.add(name) - - self.progress.inc(success) - self.progress.show() - self.state = STATE_IDLE - - def get_failed_boards(self): - """Returns a set of failed boards (defconfigs) in this slot. - """ - return self.failed_boards - -class Slots: - - """Controller of the array of subprocess slots.""" - - def __init__(self, toolchains, args, progress, reference_src_dir, db_queue, - col): - """Create a new slots controller. - - Args: - toolchains (Toolchains): Toolchains object containing toolchains - args (Namespace): Program arguments - progress (Progress): A progress indicator. - reference_src_dir (str): Determine the true starting config state - from this source tree (None for none) - db_queue (Queue): output queue to write config info for the database - col (terminal.Color): Colour object - """ - self.args = args - self.slots = [] - self.progress = progress - self.col = col - devnull = subprocess.DEVNULL - make_cmd = get_make_cmd() - for _ in range(args.jobs): - self.slots.append(Slot(toolchains, args, progress, devnull, - make_cmd, reference_src_dir, db_queue, col)) - - def add(self, defconfig): - """Add a new subprocess if a vacant slot is found. - - Args: - defconfig (str): defconfig name to be put into. - - Returns: - Return True on success or False on failure - """ - for slot in self.slots: - if slot.add(defconfig): - return True - return False - - def available(self): - """Check if there is a vacant slot. - - Returns: - Return True if at lease one vacant slot is found, False otherwise. - """ - for slot in self.slots: - if slot.poll(): - return True - return False - - def empty(self): - """Check if all slots are vacant. - - Returns: - Return True if all the slots are vacant, False otherwise. - """ - ret = True - for slot in self.slots: - if not slot.poll(): - ret = False - return ret - - def write_failed_boards(self): - """Show the results of processing""" - boards = set() - - for slot in self.slots: - boards |= slot.get_failed_boards() - - if boards: - boards = '\n'.join(sorted(boards)) + '\n' - write_file(FAILED_LIST, boards) - - -class ReferenceSource: - - """Reference source against which original configs should be parsed.""" - - def __init__(self, commit): - """Create a reference source directory based on a specified commit. - - Args: - commit: commit to git-clone - """ - self.src_dir = tempfile.mkdtemp() - print('Cloning git repo to a separate work directory...') - subprocess.check_output(['git', 'clone', os.getcwd(), '.'], - cwd=self.src_dir) - rev = subprocess.check_output(['git', 'rev-parse', '--short', - commit]).strip() - print(f"Checkout '{rev}' to build the original autoconf.mk.") - subprocess.check_output(['git', 'checkout', commit], - stderr=subprocess.STDOUT, cwd=self.src_dir) - - def __del__(self): - """Delete the reference source directory - - This function makes sure the temporary directory is cleaned away - even if Python suddenly dies due to error. It should be done in here - because it is guaranteed the destructor is always invoked when the - instance of the class gets unreferenced. - """ - shutil.rmtree(self.src_dir) - - def get_dir(self): - """Return the absolute path to the reference source directory.""" - - return self.src_dir - -def move_config(toolchains, args, db_queue, col): - """Build database or sync config options to defconfig files. - - Args: - toolchains (Toolchains): Toolchains to use - args (Namespace): Program arguments - db_queue (Queue): Queue for database updates - col (terminal.Color): Colour object - - Returns: - Progress: Progress indicator - """ - if args.git_ref: - reference_src = ReferenceSource(args.git_ref) - reference_src_dir = reference_src.get_dir() - else: - reference_src_dir = None - - if args.defconfigs: - defconfigs = get_matched_defconfigs(args.defconfigs) - else: - defconfigs = get_all_defconfigs() - - progress = Progress(col, len(defconfigs)) - slots = Slots(toolchains, args, progress, reference_src_dir, db_queue, col) - - # Main loop to process defconfig files: - # Add a new subprocess into a vacant slot. - # Sleep if there is no available slot. - for defconfig in defconfigs: - while not slots.add(defconfig): - while not slots.available(): - # No available slot: sleep for a while - time.sleep(SLEEP_TIME) - - # wait until all the subprocesses finish - while not slots.empty(): - time.sleep(SLEEP_TIME) - - slots.write_failed_boards() - return progress - -def find_kconfig_rules(kconf, config, imply_config): - """Check whether a config has a 'select' or 'imply' keyword - - Args: - kconf (Kconfiglib.Kconfig): Kconfig object - config (str): Name of config to check (without CONFIG_ prefix) - imply_config (str): Implying config (without CONFIG_ prefix) which may - or may not have an 'imply' for 'config') - - Returns: - Symbol object for 'config' if found, else None - """ - sym = kconf.syms.get(imply_config) - if sym: - for sel, _ in (sym.selects + sym.implies): - if sel.name == config: - return sym - return None - -def check_imply_rule(kconf, config, imply_config): - """Check if we can add an 'imply' option - - This finds imply_config in the Kconfig and looks to see if it is possible - to add an 'imply' for 'config' to that part of the Kconfig. - - Args: - kconf (Kconfiglib.Kconfig): Kconfig object - config (str): Name of config to check (without CONFIG_ prefix) - imply_config (str): Implying config (without CONFIG_ prefix) which may - or may not have an 'imply' for 'config') - - Returns: - tuple: - str: filename of Kconfig file containing imply_config, or None if - none - int: line number within the Kconfig file, or 0 if none - str: message indicating the result - """ - sym = kconf.syms.get(imply_config) - if not sym: - return 'cannot find sym' - nodes = sym.nodes - if len(nodes) != 1: - return f'{len(nodes)} locations' - node = nodes[0] - fname, linenum = node.filename, node.linenr - cwd = os.getcwd() - if cwd and fname.startswith(cwd): - fname = fname[len(cwd) + 1:] - file_line = f' at {fname}:{linenum}' - data = read_file(fname) - if data[linenum - 1] != f'config {imply_config}': - return None, 0, f'bad sym format {data[linenum]}{file_line})' - return fname, linenum, f'adding{file_line}' - -def add_imply_rule(config, fname, linenum): - """Add a new 'imply' option to a Kconfig - - Args: - config (str): config option to add an imply for (without CONFIG_ prefix) - fname (str): Kconfig filename to update - linenum (int): Line number to place the 'imply' before - - Returns: - Message indicating the result - """ - file_line = f' at {fname}:{linenum}' - data = read_file(fname) - linenum -= 1 - - for offset, line in enumerate(data[linenum:]): - if line.strip().startswith('help') or not line: - data.insert(linenum + offset, f'\timply {config}') - write_file(fname, data) - return f'added{file_line}' - - return 'could not insert%s' - -(IMPLY_MIN_2, IMPLY_TARGET, IMPLY_CMD, IMPLY_NON_ARCH_BOARD) = ( - 1, 2, 4, 8) - -IMPLY_FLAGS = { - 'min2': [IMPLY_MIN_2, 'Show options which imply >2 boards (normally >5)'], - 'target': [IMPLY_TARGET, 'Allow CONFIG_TARGET_... options to imply'], - 'cmd': [IMPLY_CMD, 'Allow CONFIG_CMD_... to imply'], - 'non-arch-board': [ - IMPLY_NON_ARCH_BOARD, - 'Allow Kconfig options outside arch/ and /board/ to imply'], -} - - -def read_database(): - """Read in the config database - - Returns: - tuple: - set of all config options seen (each a str) - set of all defconfigs seen (each a str) - dict of configs for each defconfig: - key: defconfig name, e.g. "MPC8548CDS_legacy_defconfig" - value: dict: - key: CONFIG option - value: Value of option - dict of defconfigs for each config: - key: CONFIG option - value: set of boards using that option - - """ - configs = {} - - # key is defconfig name, value is dict of (CONFIG_xxx, value) - config_db = {} - - # Set of all config options we have seen - all_configs = set() - - # Set of all defconfigs we have seen - all_defconfigs = set() - - defconfig_db = collections.defaultdict(set) - for line in read_file(CONFIG_DATABASE): - line = line.rstrip() - if not line: # Separator between defconfigs - config_db[defconfig] = configs - all_defconfigs.add(defconfig) - configs = {} - elif line[0] == ' ': # CONFIG line - config, value = line.strip().split('=', 1) - configs[config] = value - defconfig_db[config].add(defconfig) - all_configs.add(config) - else: # New defconfig - defconfig = line - - return all_configs, all_defconfigs, config_db, defconfig_db - - -def do_imply_config(config_list, add_imply, imply_flags, skip_added, - check_kconfig=True, find_superset=False): - """Find CONFIG options which imply those in the list - - Some CONFIG options can be implied by others and this can help to reduce - the size of the defconfig files. For example, CONFIG_X86 implies - CONFIG_CMD_IRQ, so we can put 'imply CMD_IRQ' under 'config X86' and - all x86 boards will have that option, avoiding adding CONFIG_CMD_IRQ to - each of the x86 defconfig files. - - This function uses the moveconfig database to find such options. It - displays a list of things that could possibly imply those in the list. - The algorithm ignores any that start with CONFIG_TARGET since these - typically refer to only a few defconfigs (often one). It also does not - display a config with less than 5 defconfigs. - - The algorithm works using sets. For each target config in config_list: - - Get the set 'defconfigs' which use that target config - - For each config (from a list of all configs): - - Get the set 'imply_defconfig' of defconfigs which use that config - - - - If imply_defconfigs contains anything not in defconfigs then - this config does not imply the target config - - Params: - config_list: List of CONFIG options to check (each a string) - add_imply: Automatically add an 'imply' for each config. - imply_flags: Flags which control which implying configs are allowed - (IMPLY_...) - skip_added: Don't show options which already have an imply added. - check_kconfig: Check if implied symbols already have an 'imply' or - 'select' for the target config, and show this information if so. - find_superset: True to look for configs which are a superset of those - already found. So for example if CONFIG_EXYNOS5 implies an option, - but CONFIG_EXYNOS covers a larger set of defconfigs and also - implies that option, this will drop the former in favour of the - latter. In practice this option has not proved very used. - - Note the terminoloy: - config - a CONFIG_XXX options (a string, e.g. 'CONFIG_CMD_EEPROM') - defconfig - a defconfig file (a string, e.g. 'configs/snow_defconfig') - """ - kconf = KconfigScanner().conf if check_kconfig else None - if add_imply and add_imply != 'all': - add_imply = add_imply.split(',') - - all_configs, all_defconfigs, _, defconfig_db = read_database() - - # Work through each target config option in turn, independently - for config in config_list: - defconfigs = defconfig_db.get(config) - if not defconfigs: - print(f'{config} not found in any defconfig') - continue - - # Get the set of defconfigs without this one (since a config cannot - # imply itself) - non_defconfigs = all_defconfigs - defconfigs - num_defconfigs = len(defconfigs) - print(f'{config} found in {num_defconfigs}/{len(all_configs)} defconfigs') - - # This will hold the results: key=config, value=defconfigs containing it - imply_configs = {} - rest_configs = all_configs - set([config]) - - # Look at every possible config, except the target one - for imply_config in rest_configs: - if 'ERRATUM' in imply_config: - continue - if not imply_flags & IMPLY_CMD: - if 'CONFIG_CMD' in imply_config: - continue - if not imply_flags & IMPLY_TARGET: - if 'CONFIG_TARGET' in imply_config: - continue - - # Find set of defconfigs that have this config - imply_defconfig = defconfig_db[imply_config] - - # Get the intersection of this with defconfigs containing the - # target config - common_defconfigs = imply_defconfig & defconfigs - - # Get the set of defconfigs containing this config which DO NOT - # also contain the taret config. If this set is non-empty it means - # that this config affects other defconfigs as well as (possibly) - # the ones affected by the target config. This means it implies - # things we don't want to imply. - not_common_defconfigs = imply_defconfig & non_defconfigs - if not_common_defconfigs: - continue - - # If there are common defconfigs, imply_config may be useful - if common_defconfigs: - skip = False - if find_superset: - for prev in list(imply_configs.keys()): - prev_count = len(imply_configs[prev]) - count = len(common_defconfigs) - if (prev_count > count and - (imply_configs[prev] & common_defconfigs == - common_defconfigs)): - # skip imply_config because prev is a superset - skip = True - break - if count > prev_count: - # delete prev because imply_config is a superset - del imply_configs[prev] - if not skip: - imply_configs[imply_config] = common_defconfigs - - # Now we have a dict imply_configs of configs which imply each config - # The value of each dict item is the set of defconfigs containing that - # config. Rank them so that we print the configs that imply the largest - # number of defconfigs first. - ranked_iconfigs = sorted(imply_configs, - key=lambda k: len(imply_configs[k]), reverse=True) - kconfig_info = '' - cwd = os.getcwd() - add_list = collections.defaultdict(list) - for iconfig in ranked_iconfigs: - num_common = len(imply_configs[iconfig]) - - # Don't bother if there are less than 5 defconfigs affected. - if num_common < (2 if imply_flags & IMPLY_MIN_2 else 5): - continue - missing = defconfigs - imply_configs[iconfig] - missing_str = ', '.join(missing) if missing else 'all' - missing_str = '' - show = True - if kconf: - sym = find_kconfig_rules(kconf, config[CONFIG_LEN:], - iconfig[CONFIG_LEN:]) - kconfig_info = '' - if sym: - nodes = sym.nodes - if len(nodes) == 1: - fname, linenum = nodes[0].filename, nodes[0].linenr - if cwd and fname.startswith(cwd): - fname = fname[len(cwd) + 1:] - kconfig_info = f'{fname}:{linenum}' - if skip_added: - show = False - else: - sym = kconf.syms.get(iconfig[CONFIG_LEN:]) - fname = '' - if sym: - nodes = sym.nodes - if len(nodes) == 1: - fname, linenum = nodes[0].filename, nodes[0].linenr - if cwd and fname.startswith(cwd): - fname = fname[len(cwd) + 1:] - in_arch_board = not sym or (fname.startswith('arch') or - fname.startswith('board')) - if (not in_arch_board and - not imply_flags & IMPLY_NON_ARCH_BOARD): - continue - - if add_imply and (add_imply == 'all' or - iconfig in add_imply): - fname, linenum, kconfig_info = (check_imply_rule(kconf, - config[CONFIG_LEN:], iconfig[CONFIG_LEN:])) - if fname: - add_list[fname].append(linenum) - - if show and kconfig_info != 'skip': - print(f'{num_common:5d} : ' - f'{iconfig.ljust(30):-30s}{kconfig_info:-25s} {missing_str}') - - # Having collected a list of things to add, now we add them. We process - # each file from the largest line number to the smallest so that - # earlier additions do not affect our line numbers. E.g. if we added an - # imply at line 20 it would change the position of each line after - # that. - for fname, linenums in add_list.items(): - for linenum in sorted(linenums, reverse=True): - add_imply_rule(config[CONFIG_LEN:], fname, linenum) - -def defconfig_matches(configs, re_match): - """Check if any CONFIG option matches a regex - - The match must be complete, i.e. from the start to end of the CONFIG option. - - Args: - configs (dict): Dict of CONFIG options: - key: CONFIG option - value: Value of option - re_match (re.Pattern): Match to check - - Returns: - bool: True if any CONFIG matches the regex - """ - for cfg in configs: - if re_match.fullmatch(cfg): - return True - return False - -def do_find_config(config_list): - """Find boards with a given combination of CONFIGs - - Params: - config_list: List of CONFIG options to check (each a regex consisting - of a config option, with or without a CONFIG_ prefix. If an option - is preceded by a tilde (~) then it must be false, otherwise it must - be true) - """ - _, all_defconfigs, config_db, _ = read_database() - - # Start with all defconfigs - out = all_defconfigs - - # Work through each config in turn - for item in config_list: - # Get the real config name and whether we want this config or not - cfg = item - want = True - if cfg[0] == '~': - want = False - cfg = cfg[1:] - - # Search everything that is still in the running. If it has a config - # that we want, or doesn't have one that we don't, add it into the - # running for the next stage - in_list = out - out = set() - re_match = re.compile(cfg) - for defc in in_list: - has_cfg = defconfig_matches(config_db[defc], re_match) - if has_cfg == want: - out.add(defc) - print(f'{len(out)} matches') - print(' '.join(item.split('_defconfig')[0] for item in out)) - - -def prefix_config(cfg): - """Prefix a config with CONFIG_ if needed - - This handles ~ operator, which indicates that the CONFIG should be disabled - - >>> prefix_config('FRED') - 'CONFIG_FRED' - >>> prefix_config('CONFIG_FRED') - 'CONFIG_FRED' - >>> prefix_config('~FRED') - '~CONFIG_FRED' - >>> prefix_config('~CONFIG_FRED') - '~CONFIG_FRED' - >>> prefix_config('A123') - 'CONFIG_A123' - """ - oper = '' - if cfg[0] == '~': - oper = cfg[0] - cfg = cfg[1:] - if not cfg.startswith('CONFIG_'): - cfg = 'CONFIG_' + cfg - return oper + cfg - - -RE_MK_CONFIGS = re.compile(r'CONFIG_(\$\(SPL_(?:TPL_)?\))?([A-Za-z0-9_]*)') -RE_IFDEF = re.compile(r'(ifdef|ifndef)') -RE_C_CONFIGS = re.compile(r'CONFIG_([A-Za-z0-9_]*)') -RE_CONFIG_IS = re.compile(r'CONFIG_IS_ENABLED\(([A-Za-z0-9_]*)\)') - -class ConfigUse: - def __init__(self, cfg, is_spl, fname, rest): - self.cfg = cfg - self.is_spl = is_spl - self.fname = fname - self.rest = rest - - def __hash__(self): - return hash((self.cfg, self.is_spl)) - -def scan_makefiles(fnames): - """Scan Makefiles looking for Kconfig options - - Looks for uses of CONFIG options in Makefiles - - Args: - fnames (list of tuple): - str: Makefile filename where the option was found - str: Line of the Makefile - - Returns: - tuple: - dict: all_uses - key (ConfigUse): object - value (list of str): matching lines - dict: Uses by filename - key (str): filename - value (set of ConfigUse): uses in that filename - - >>> RE_MK_CONFIGS.search('CONFIG_FRED').groups() - (None, 'FRED') - >>> RE_MK_CONFIGS.search('CONFIG_$(SPL_)MARY').groups() - ('$(SPL_)', 'MARY') - >>> RE_MK_CONFIGS.search('CONFIG_$(SPL_TPL_)MARY').groups() - ('$(SPL_TPL_)', 'MARY') - """ - all_uses = collections.defaultdict(list) - fname_uses = {} - for fname, rest in fnames: - m_iter = RE_MK_CONFIGS.finditer(rest) - for mat in m_iter: - real_opt = mat.group(2) - if real_opt == '': - continue - is_spl = False - if mat.group(1): - is_spl = True - use = ConfigUse(real_opt, is_spl, fname, rest) - if fname not in fname_uses: - fname_uses[fname] = set() - fname_uses[fname].add(use) - all_uses[use].append(rest) - return all_uses, fname_uses - - -def scan_src_files(fnames): - """Scan source files (other than Makefiles) looking for Kconfig options - - Looks for uses of CONFIG options - - Args: - fnames (list of tuple): - str: Makefile filename where the option was found - str: Line of the Makefile - - Returns: - tuple: - dict: all_uses - key (ConfigUse): object - value (list of str): matching lines - dict: Uses by filename - key (str): filename - value (set of ConfigUse): uses in that filename - - >>> RE_C_CONFIGS.search('CONFIG_FRED').groups() - ('FRED',) - >>> RE_CONFIG_IS.search('CONFIG_IS_ENABLED(MARY)').groups() - ('MARY',) - >>> RE_CONFIG_IS.search('#if CONFIG_IS_ENABLED(OF_PLATDATA)').groups() - ('OF_PLATDATA',) - """ - fname = None - rest = None - - def add_uses(m_iter, is_spl): - for mat in m_iter: - real_opt = mat.group(1) - if real_opt == '': - continue - use = ConfigUse(real_opt, is_spl, fname, rest) - if fname not in fname_uses: - fname_uses[fname] = set() - fname_uses[fname].add(use) - all_uses[use].append(rest) - - all_uses = collections.defaultdict(list) - fname_uses = {} - for fname, rest in fnames: - m_iter = RE_C_CONFIGS.finditer(rest) - add_uses(m_iter, False) - - m_iter2 = RE_CONFIG_IS.finditer(rest) - add_uses(m_iter2, True) - - return all_uses, fname_uses - - -MODE_NORMAL, MODE_SPL, MODE_PROPER = range(3) - -def do_scan_source(path, do_update): - """Scan the source tree for Kconfig inconsistencies - - Args: - path (str): Path to source tree - do_update (bool) : True to write to scripts/kconf_... files - """ - def is_not_proper(name): - for prefix in SPL_PREFIXES: - if name.startswith(prefix): - return name[len(prefix):] - return False - - def check_not_found(all_uses, spl_mode): - """Check for Kconfig options mentioned in the source but not in Kconfig - - Args: - all_uses (dict): - key (ConfigUse): object - value (list of str): matching lines - spl_mode (int): If MODE_SPL, look at source code which implies - an SPL_ option, but for which there is none; - for MOD_PROPER, look at source code which implies a Proper - option (i.e. use of CONFIG_IS_ENABLED() or $(SPL_) or - $(SPL_TPL_) but for which there none; - if MODE_NORMAL, ignore SPL - - Returns: - dict: - key (str): CONFIG name (without 'CONFIG_' prefix - value (list of ConfigUse): List of uses of this CONFIG - """ - # Make sure we know about all the options - not_found = collections.defaultdict(list) - for use, _ in all_uses.items(): - name = use.cfg - if name in IGNORE_SYMS: - continue - check = True - - if spl_mode == MODE_SPL: - check = use.is_spl - - # If it is an SPL symbol, try prepending all SPL_ prefixes to - # find at least one SPL symbol - if use.is_spl: - for prefix in SPL_PREFIXES: - try_name = prefix + name - sym = kconf.syms.get(try_name) - if sym: - break - if not sym: - not_found[f'SPL_{name}'].append(use) - continue - elif spl_mode == MODE_PROPER: - # Try to find the Proper version of this symbol, i.e. without - # the SPL_ prefix - proper_name = is_not_proper(name) - if proper_name: - name = proper_name - elif not use.is_spl: - check = False - else: # MODE_NORMAL - sym = kconf.syms.get(name) - if not sym: - proper_name = is_not_proper(name) - if proper_name: - name = proper_name - sym = kconf.syms.get(name) - if not sym: - for prefix in SPL_PREFIXES: - try_name = prefix + name - sym = kconf.syms.get(try_name) - if sym: - break - if not sym: - not_found[name].append(use) - continue - - sym = kconf.syms.get(name) - if not sym and check: - not_found[name].append(use) - return not_found - - def show_uses(uses): - """Show a list of uses along with their filename and code snippet - - Args: - uses (dict): - key (str): CONFIG name (without 'CONFIG_' prefix - value (list of ConfigUse): List of uses of this CONFIG - """ - for name in sorted(uses): - print(f'{name}: ', end='') - for i, use in enumerate(uses[name]): - print(f'{" " if i else ""}{use.fname}: {use.rest.strip()}') - - - print('Scanning Kconfig') - kconf = KconfigScanner().conf - print(f'Scanning source in {path}') - args = ['git', 'grep', '-E', r'IS_ENABLED|\bCONFIG'] - with subprocess.Popen(args, stdout=subprocess.PIPE) as proc: - out, _ = proc.communicate() - lines = out.splitlines() - re_fname = re.compile('^([^:]*):(.*)') - src_list = [] - mk_list = [] - for line in lines: - linestr = line.decode('utf-8') - m_fname = re_fname.search(linestr) - if not m_fname: - continue - fname, rest = m_fname.groups() - dirname, leaf = os.path.split(fname) - root, ext = os.path.splitext(leaf) - if ext == '.autoconf': - pass - elif ext in ['.c', '.h', '.S', '.lds', '.dts', '.dtsi', '.asl', '.cfg', - '.env', '.tmpl']: - src_list.append([fname, rest]) - elif 'Makefile' in root or ext == '.mk': - mk_list.append([fname, rest]) - elif ext in ['.yml', '.sh', '.py', '.awk', '.pl', '.rst', '', '.sed']: - pass - elif 'Kconfig' in root or 'Kbuild' in root: - pass - elif 'README' in root: - pass - elif dirname in ['configs']: - pass - elif dirname.startswith('doc') or dirname.startswith('scripts/kconfig'): - pass - else: - print(f'Not sure how to handle file {fname}') - - # Scan the Makefiles - all_uses, _ = scan_makefiles(mk_list) - - spl_not_found = set() - proper_not_found = set() - - # Make sure we know about all the options - print('\nCONFIG options present in Makefiles but not Kconfig:') - not_found = check_not_found(all_uses, MODE_NORMAL) - show_uses(not_found) - - print('\nCONFIG options present in Makefiles but not Kconfig (SPL):') - not_found = check_not_found(all_uses, MODE_SPL) - show_uses(not_found) - spl_not_found |= {is_not_proper(key) or key for key in not_found.keys()} - - print('\nCONFIG options used as Proper in Makefiles but without a non-SPL_ variant:') - not_found = check_not_found(all_uses, MODE_PROPER) - show_uses(not_found) - proper_not_found |= {not_found.keys()} - - # Scan the source code - all_uses, _ = scan_src_files(src_list) - - # Make sure we know about all the options - print('\nCONFIG options present in source but not Kconfig:') - not_found = check_not_found(all_uses, MODE_NORMAL) - show_uses(not_found) - - print('\nCONFIG options present in source but not Kconfig (SPL):') - not_found = check_not_found(all_uses, MODE_SPL) - show_uses(not_found) - spl_not_found |= {is_not_proper(key) or key for key in not_found.keys()} - - print('\nCONFIG options used as Proper in source but without a non-SPL_ variant:') - not_found = check_not_found(all_uses, MODE_PROPER) - show_uses(not_found) - proper_not_found |= {not_found.keys()} - - print('\nCONFIG options used as SPL but without an SPL_ variant:') - for item in sorted(spl_not_found): - print(f' {item}') - - print('\nCONFIG options used as Proper but without a non-SPL_ variant:') - for item in sorted(proper_not_found): - print(f' {item}') - - # Write out the updated information - if do_update: - with open(os.path.join(path, 'scripts', 'conf_nospl'), 'w', - encoding='utf-8') as out: - print('# These options should not be enabled in SPL builds\n', - file=out) - for item in sorted(spl_not_found): - print(item, file=out) - with open(os.path.join(path, 'scripts', 'conf_noproper'), 'w', - encoding='utf-8') as out: - print('# These options should not be enabled in Proper builds\n', - file=out) - for item in sorted(proper_not_found): - print(item, file=out) - - -def main(): - try: - cpu_count = multiprocessing.cpu_count() - except NotImplementedError: - cpu_count = 1 - - epilog = '''Move config options from headers to defconfig files. See -doc/develop/moveconfig.rst for documentation.''' - - parser = ArgumentParser(epilog=epilog) - # Add arguments here - parser.add_argument('-a', '--add-imply', type=str, default='', - help='comma-separated list of CONFIG options to add ' - "an 'imply' statement to for the CONFIG in -i") - parser.add_argument('-A', '--skip-added', action='store_true', default=False, - help="don't show options which are already marked as " - 'implying others') - parser.add_argument('-b', '--build-db', action='store_true', default=False, - help='build a CONFIG database') - parser.add_argument('-C', '--commit', action='store_true', default=False, - help='Create a git commit for the operation') - parser.add_argument('--nocolour', action='store_true', default=False, - help="don't display the log in colour") - parser.add_argument('-d', '--defconfigs', type=str, - help='a file containing a list of defconfigs to move, ' - "one per line (for example 'snow_defconfig') " - "or '-' to read from stdin") - parser.add_argument('-e', '--exit-on-error', action='store_true', - default=False, - help='exit immediately on any error') - parser.add_argument('-f', '--find', action='store_true', default=False, - help='Find boards with a given config combination') - parser.add_argument('-i', '--imply', action='store_true', default=False, - help='find options which imply others') - parser.add_argument('-I', '--imply-flags', type=str, default='', - help="control the -i option ('help' for help") - parser.add_argument('-j', '--jobs', type=int, default=cpu_count, - help='the number of jobs to run simultaneously') - parser.add_argument('-n', '--dry-run', action='store_true', default=False, - help='perform a trial run (show log with no changes)') - parser.add_argument('-r', '--git-ref', type=str, - help='the git ref to clone for building the autoconf.mk') - parser.add_argument('-s', '--force-sync', action='store_true', default=False, - help='force sync by savedefconfig') - parser.add_argument('-S', '--spl', action='store_true', default=False, - help='parse config options defined for SPL build') - parser.add_argument('--scan-source', action='store_true', default=False, - help='scan source for uses of CONFIG options') - parser.add_argument('-t', '--test', action='store_true', default=False, - help='run unit tests') - parser.add_argument('-y', '--yes', action='store_true', default=False, - help="respond 'yes' to any prompts") - parser.add_argument('-u', '--update', action='store_true', default=False, - help="update scripts/ files (use with --scan-source)") - parser.add_argument('-v', '--verbose', action='store_true', default=False, - help='show any build errors as boards are built') - parser.add_argument('configs', nargs='*') - - args = parser.parse_args() - - if args.test: - sys.argv = [sys.argv[0]] - fail, _ = doctest.testmod() - if fail: - return 1 - unittest.main() - - col = terminal.Color(terminal.COLOR_NEVER if args.nocolour - else terminal.COLOR_IF_TERMINAL) - - if args.scan_source: - do_scan_source(os.getcwd(), args.update) - return 0 - - if not any((args.force_sync, args.build_db, args.imply, args.find)): - parser.print_usage() - sys.exit(1) - - # prefix the option name with CONFIG_ if missing - configs = [prefix_config(cfg) for cfg in args.configs] - - check_top_directory() - - if args.imply: - imply_flags = 0 - if args.imply_flags == 'all': - imply_flags = -1 - - elif args.imply_flags: - for flag in args.imply_flags.split(','): - bad = flag not in IMPLY_FLAGS - if bad: - print(f"Invalid flag '{flag}'") - if flag == 'help' or bad: - print("Imply flags: (separate with ',')") - for name, info in IMPLY_FLAGS.items(): - print(f' {name:-15s}: {info[1]}') - parser.print_usage() - sys.exit(1) - imply_flags |= IMPLY_FLAGS[flag][0] - - do_imply_config(configs, args.add_imply, imply_flags, args.skip_added) - return 0 - - if args.find: - do_find_config(configs) - return 0 - - # We are either building the database or forcing a sync of defconfigs - config_db = {} - db_queue = queue.Queue() - dbt = DatabaseThread(config_db, db_queue) - dbt.daemon = True - dbt.start() - - check_clean_directory() - bsettings.setup('') - toolchains = toolchain.Toolchains() - toolchains.GetSettings() - toolchains.Scan(verbose=False) - progress = move_config(toolchains, args, db_queue, col) - db_queue.join() - - if args.commit: - subprocess.call(['git', 'add', '-u']) - if configs: - msg = 'Convert %s %sto Kconfig' % (configs[0], - 'et al ' if len(configs) > 1 else '') - msg += ('\n\nThis converts the following to Kconfig:\n %s\n' % - '\n '.join(configs)) - else: - msg = 'configs: Resync with savedefconfig' - msg += '\n\nRsync all defconfig files using moveconfig.py' - subprocess.call(['git', 'commit', '-s', '-m', msg]) - - failed = progress.total - progress.good - failure = f'{failed} failed, ' if failed else '' - if args.build_db: - with open(CONFIG_DATABASE, 'w', encoding='utf-8') as outf: - for defconfig, configs in config_db.items(): - outf.write(f'{defconfig}\n') - for config in sorted(configs.keys()): - outf.write(f' {config}={configs[config]}\n') - outf.write('\n') - print(col.build( - col.RED if failed else col.GREEN, - f'{failure}{len(config_db)} boards written to {CONFIG_DATABASE}')) - else: - if failed: - print(col.build(col.RED, f'{failure}see {FAILED_LIST}', True)) - else: - # Add enough spaces to overwrite the progress indicator - print(col.build( - col.GREEN, f'{progress.total} processed ', bright=True)) - - return 0 - - -if __name__ == '__main__': - sys.exit(main()) diff --git a/tools/qconfig.py b/tools/qconfig.py new file mode 100755 index 0000000..dd55a69 --- /dev/null +++ b/tools/qconfig.py @@ -0,0 +1,1624 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0+ +# +# Author: Masahiro Yamada +# + +""" +Build and query a Kconfig database for boards. + +See doc/develop/moveconfig.rst for documentation. +""" + +from argparse import ArgumentParser +import collections +from contextlib import ExitStack +import doctest +import filecmp +import fnmatch +import glob +import multiprocessing +import os +import queue +import re +import shutil +import subprocess +import sys +import tempfile +import threading +import time +import unittest + +import asteval +from buildman import bsettings +from buildman import kconfiglib +from buildman import toolchain +from u_boot_pylib import terminal + +SHOW_GNU_MAKE = 'scripts/show-gnu-make' +SLEEP_TIME=0.03 + +STATE_IDLE = 0 +STATE_DEFCONFIG = 1 +STATE_AUTOCONF = 2 +STATE_SAVEDEFCONFIG = 3 + +AUTO_CONF_PATH = 'include/config/auto.conf' +CONFIG_DATABASE = 'moveconfig.db' +FAILED_LIST = 'moveconfig.failed' + +CONFIG_LEN = len('CONFIG_') + +SIZES = { + 'SZ_1': 0x00000001, 'SZ_2': 0x00000002, + 'SZ_4': 0x00000004, 'SZ_8': 0x00000008, + 'SZ_16': 0x00000010, 'SZ_32': 0x00000020, + 'SZ_64': 0x00000040, 'SZ_128': 0x00000080, + 'SZ_256': 0x00000100, 'SZ_512': 0x00000200, + 'SZ_1K': 0x00000400, 'SZ_2K': 0x00000800, + 'SZ_4K': 0x00001000, 'SZ_8K': 0x00002000, + 'SZ_16K': 0x00004000, 'SZ_32K': 0x00008000, + 'SZ_64K': 0x00010000, 'SZ_128K': 0x00020000, + 'SZ_256K': 0x00040000, 'SZ_512K': 0x00080000, + 'SZ_1M': 0x00100000, 'SZ_2M': 0x00200000, + 'SZ_4M': 0x00400000, 'SZ_8M': 0x00800000, + 'SZ_16M': 0x01000000, 'SZ_32M': 0x02000000, + 'SZ_64M': 0x04000000, 'SZ_128M': 0x08000000, + 'SZ_256M': 0x10000000, 'SZ_512M': 0x20000000, + 'SZ_1G': 0x40000000, 'SZ_2G': 0x80000000, + 'SZ_4G': 0x100000000 +} + +RE_REMOVE_DEFCONFIG = re.compile(r'(.*)_defconfig') + +# CONFIG symbols present in the build system (from Linux) but not actually used +# in U-Boot; KCONFIG symbols +IGNORE_SYMS = ['DEBUG_SECTION_MISMATCH', 'FTRACE_MCOUNT_RECORD', 'GCOV_KERNEL', + 'GCOV_PROFILE_ALL', 'KALLSYMS', 'KASAN', 'MODVERSIONS', 'SHELL', + 'TPL_BUILD', 'VPL_BUILD', 'IS_ENABLED', 'FOO', 'IF_ENABLED_INT', + 'IS_ENABLED_', 'IS_ENABLED_1', 'IS_ENABLED_2', 'IS_ENABLED_3', + 'SPL_', 'TPL_', 'SPL_FOO', 'TPL_FOO', 'TOOLS_FOO', + 'ACME', 'SPL_ACME', 'TPL_ACME', 'TRACE_BRANCH_PROFILING', + 'VAL', '_UNDEFINED', 'SPL_BUILD', ] + +SPL_PREFIXES = ['SPL_', 'TPL_', 'VPL_', 'TOOLS_'] + +### helper functions ### +def check_top_directory(): + """Exit if we are not at the top of source directory.""" + for fname in 'README', 'Licenses': + if not os.path.exists(fname): + sys.exit('Please run at the top of source directory.') + +def check_clean_directory(): + """Exit if the source tree is not clean.""" + for fname in '.config', 'include/config': + if os.path.exists(fname): + sys.exit("source tree is not clean, please run 'make mrproper'") + +def get_make_cmd(): + """Get the command name of GNU Make. + + U-Boot needs GNU Make for building, but the command name is not + necessarily "make". (for example, "gmake" on FreeBSD). + Returns the most appropriate command name on your system. + """ + with subprocess.Popen([SHOW_GNU_MAKE], stdout=subprocess.PIPE) as proc: + ret = proc.communicate() + if proc.returncode: + sys.exit('GNU Make not found') + return ret[0].rstrip() + +def get_matched_defconfig(line): + """Get the defconfig files that match a pattern + + Args: + line (str): Path or filename to match, e.g. 'configs/snow_defconfig' or + 'k2*_defconfig'. If no directory is provided, 'configs/' is + prepended + + Returns: + list of str: a list of matching defconfig files + """ + dirname = os.path.dirname(line) + if dirname: + pattern = line + else: + pattern = os.path.join('configs', line) + return glob.glob(pattern) + glob.glob(pattern + '_defconfig') + +def get_matched_defconfigs(defconfigs_file): + """Get all the defconfig files that match the patterns in a file. + + Args: + defconfigs_file (str): File containing a list of defconfigs to process, + or '-' to read the list from stdin + + Returns: + list of str: A list of paths to defconfig files, with no duplicates + """ + defconfigs = [] + with ExitStack() as stack: + if defconfigs_file == '-': + inf = sys.stdin + defconfigs_file = 'stdin' + else: + inf = stack.enter_context(open(defconfigs_file, encoding='utf-8')) + for i, line in enumerate(inf): + line = line.strip() + if not line: + continue # skip blank lines silently + if ' ' in line: + line = line.split(' ')[0] # handle 'git log' input + matched = get_matched_defconfig(line) + if not matched: + print(f"warning: {defconfigs_file}:{i + 1}: no defconfig matched '{line}'", + file=sys.stderr) + + defconfigs += matched + + # use set() to drop multiple matching + return [defconfig[len('configs') + 1:] for defconfig in set(defconfigs)] + +def get_all_defconfigs(): + """Get all the defconfig files under the configs/ directory. + + Returns: + list of str: List of paths to defconfig files + """ + defconfigs = [] + for (dirpath, _, filenames) in os.walk('configs'): + dirpath = dirpath[len('configs') + 1:] + for filename in fnmatch.filter(filenames, '*_defconfig'): + defconfigs.append(os.path.join(dirpath, filename)) + + return defconfigs + +def write_file(fname, data): + """Write data to a file + + Args: + fname (str): Filename to write to + data (list of str): Lines to write (with or without trailing newline); + or str to write + """ + with open(fname, 'w', encoding='utf-8') as out: + if isinstance(data, list): + for line in data: + print(line.rstrip('\n'), file=out) + else: + out.write(data) + +def read_file(fname, as_lines=True, skip_unicode=False): + """Read a file and return the contents + + Args: + fname (str): Filename to read from + as_lines (bool): Return file contents as a list of lines + skip_unicode (bool): True to report unicode errors and continue + + Returns: + iter of str: List of ;ines from the file with newline removed; str if + as_lines is False with newlines intact; or None if a unicode error + occurred + + Raises: + UnicodeDecodeError: Unicode error occurred when reading + """ + with open(fname, encoding='utf-8') as inf: + try: + if as_lines: + return [line.rstrip('\n') for line in inf.readlines()] + return inf.read() + except UnicodeDecodeError as exc: + if not skip_unicode: + raise + print(f"Failed on file '{fname}: {exc}") + return None + +def try_expand(line): + """If value looks like an expression, try expanding it + Otherwise just return the existing value + """ + if line.find('=') == -1: + return line + + try: + aeval = asteval.Interpreter( usersyms=SIZES, minimal=True ) + cfg, val = re.split("=", line) + val= val.strip('\"') + if re.search(r'[*+-/]|<<|SZ_+|\(([^\)]+)\)', val): + newval = hex(aeval(val)) + print(f'\tExpanded expression {val} to {newval}') + return cfg+'='+newval + except: + print(f'\tFailed to expand expression in {line}') + + return line + + +### classes ### +class Progress: + + """Progress Indicator""" + + def __init__(self, col, total): + """Create a new progress indicator. + + Args: + color_enabled (bool): True for colour output + total (int): A number of defconfig files to process. + """ + self.col = col + self.current = 0 + self.good = 0 + self.total = total + + def inc(self, success): + """Increment the number of processed defconfig files. + + Args: + success (bool): True if processing succeeded + """ + self.good += success + self.current += 1 + + def show(self): + """Display the progress.""" + if self.current != self.total: + line = self.col.build(self.col.GREEN, f'{self.good:5d}') + line += self.col.build(self.col.RED, + f'{self.current - self.good:5d}') + line += self.col.build(self.col.MAGENTA, + f'/{self.total - self.current}') + print(f'{line} \r', end='') + sys.stdout.flush() + + +class KconfigScanner: + """Kconfig scanner.""" + + def __init__(self): + """Scan all the Kconfig files and create a Config object.""" + # Define environment variables referenced from Kconfig + os.environ['srctree'] = os.getcwd() + os.environ['UBOOTVERSION'] = 'dummy' + os.environ['KCONFIG_OBJDIR'] = '' + os.environ['CC'] = 'gcc' + self.conf = kconfiglib.Kconfig() + + +class KconfigParser: + + """A parser of .config and include/autoconf.mk.""" + + re_arch = re.compile(r'CONFIG_SYS_ARCH="(.*)"') + re_cpu = re.compile(r'CONFIG_SYS_CPU="(.*)"') + + def __init__(self, args, build_dir): + """Create a new parser. + + Args: + args (Namespace): program arguments + build_dir: Build directory. + """ + self.args = args + self.dotconfig = os.path.join(build_dir, '.config') + self.autoconf = os.path.join(build_dir, 'include', 'autoconf.mk') + self.spl_autoconf = os.path.join(build_dir, 'spl', 'include', + 'autoconf.mk') + self.config_autoconf = os.path.join(build_dir, AUTO_CONF_PATH) + self.defconfig = os.path.join(build_dir, 'defconfig') + + def get_arch(self): + """Parse .config file and return the architecture. + + Returns: + Architecture name (e.g. 'arm'). + """ + arch = '' + cpu = '' + for line in read_file(self.dotconfig): + m_arch = self.re_arch.match(line) + if m_arch: + arch = m_arch.group(1) + continue + m_cpu = self.re_cpu.match(line) + if m_cpu: + cpu = m_cpu.group(1) + + if not arch: + return None + + # fix-up for aarch64 + if arch == 'arm' and cpu == 'armv8': + arch = 'aarch64' + + return arch + + +class DatabaseThread(threading.Thread): + """This thread processes results from Slot threads. + + It collects the data in the master config directary. There is only one + result thread, and this helps to serialise the build output. + """ + def __init__(self, config_db, db_queue): + """Set up a new result thread + + Args: + builder: Builder which will be sent each result + """ + threading.Thread.__init__(self) + self.config_db = config_db + self.db_queue= db_queue + + def run(self): + """Called to start up the result thread. + + We collect the next result job and pass it on to the build. + """ + while True: + defconfig, configs = self.db_queue.get() + self.config_db[defconfig] = configs + self.db_queue.task_done() + + +class Slot: + + """A slot to store a subprocess. + + Each instance of this class handles one subprocess. + This class is useful to control multiple threads + for faster processing. + """ + + def __init__(self, toolchains, args, progress, devnull, make_cmd, + reference_src_dir, db_queue, col): + """Create a new process slot. + + Args: + toolchains: Toolchains object containing toolchains. + args: Program arguments + progress: A progress indicator. + devnull: A file object of '/dev/null'. + make_cmd: command name of GNU Make. + reference_src_dir: Determine the true starting config state from this + source tree. + db_queue: output queue to write config info for the database + col (terminal.Color): Colour object + """ + self.toolchains = toolchains + self.args = args + self.progress = progress + self.build_dir = tempfile.mkdtemp() + self.devnull = devnull + self.make_cmd = (make_cmd, 'O=' + self.build_dir) + self.reference_src_dir = reference_src_dir + self.db_queue = db_queue + self.col = col + self.parser = KconfigParser(args, self.build_dir) + self.state = STATE_IDLE + self.failed_boards = set() + self.defconfig = None + self.log = [] + self.current_src_dir = None + self.proc = None + + def __del__(self): + """Delete the working directory + + This function makes sure the temporary directory is cleaned away + even if Python suddenly dies due to error. It should be done in here + because it is guaranteed the destructor is always invoked when the + instance of the class gets unreferenced. + + If the subprocess is still running, wait until it finishes. + """ + if self.state != STATE_IDLE: + while self.proc.poll() is None: + pass + shutil.rmtree(self.build_dir) + + def add(self, defconfig): + """Assign a new subprocess for defconfig and add it to the slot. + + If the slot is vacant, create a new subprocess for processing the + given defconfig and add it to the slot. Just returns False if + the slot is occupied (i.e. the current subprocess is still running). + + Args: + defconfig (str): defconfig name. + + Returns: + Return True on success or False on failure + """ + if self.state != STATE_IDLE: + return False + + self.defconfig = defconfig + self.log = [] + self.current_src_dir = self.reference_src_dir + self.do_defconfig() + return True + + def poll(self): + """Check the status of the subprocess and handle it as needed. + + Returns True if the slot is vacant (i.e. in idle state). + If the configuration is successfully finished, assign a new + subprocess to build include/autoconf.mk. + If include/autoconf.mk is generated, invoke the parser to + parse the .config and the include/autoconf.mk, moving + config options to the .config as needed. + If the .config was updated, run "make savedefconfig" to sync + it, update the original defconfig, and then set the slot back + to the idle state. + + Returns: + Return True if the subprocess is terminated, False otherwise + """ + if self.state == STATE_IDLE: + return True + + if self.proc.poll() is None: + return False + + if self.proc.poll() != 0: + self.handle_error() + elif self.state == STATE_DEFCONFIG: + if self.reference_src_dir and not self.current_src_dir: + self.do_savedefconfig() + else: + self.do_autoconf() + elif self.state == STATE_AUTOCONF: + if self.current_src_dir: + self.current_src_dir = None + self.do_defconfig() + elif self.args.build_db: + self.do_build_db() + else: + self.do_savedefconfig() + elif self.state == STATE_SAVEDEFCONFIG: + self.update_defconfig() + else: + sys.exit('Internal Error. This should not happen.') + + return self.state == STATE_IDLE + + def handle_error(self): + """Handle error cases.""" + + self.log.append(self.col.build(self.col.RED, 'Failed to process', + bright=True)) + if self.args.verbose: + for line in self.proc.stderr.read().decode().splitlines(): + self.log.append(self.col.build(self.col.CYAN, line, True)) + self.finish(False) + + def do_defconfig(self): + """Run 'make _defconfig' to create the .config file.""" + + cmd = list(self.make_cmd) + cmd.append(self.defconfig) + self.proc = subprocess.Popen(cmd, stdout=self.devnull, + stderr=subprocess.PIPE, + cwd=self.current_src_dir) + self.state = STATE_DEFCONFIG + + def do_autoconf(self): + """Run 'make AUTO_CONF_PATH'.""" + + arch = self.parser.get_arch() + try: + tchain = self.toolchains.Select(arch) + except ValueError: + self.log.append(self.col.build( + self.col.YELLOW, + f"Tool chain for '{arch}' is missing: do nothing")) + self.finish(False) + return + env = tchain.MakeEnvironment(False) + + cmd = list(self.make_cmd) + cmd.append('KCONFIG_IGNORE_DUPLICATES=1') + cmd.append(AUTO_CONF_PATH) + self.proc = subprocess.Popen(cmd, stdout=self.devnull, env=env, + stderr=subprocess.PIPE, + cwd=self.current_src_dir) + self.state = STATE_AUTOCONF + + def do_build_db(self): + """Add the board to the database""" + configs = {} + for line in read_file(os.path.join(self.build_dir, AUTO_CONF_PATH)): + if line.startswith('CONFIG'): + config, value = line.split('=', 1) + configs[config] = value.rstrip() + self.db_queue.put([self.defconfig, configs]) + self.finish(True) + + def do_savedefconfig(self): + """Update the .config and run 'make savedefconfig'.""" + if not self.args.force_sync: + self.finish(True) + return + + cmd = list(self.make_cmd) + cmd.append('savedefconfig') + self.proc = subprocess.Popen(cmd, stdout=self.devnull, + stderr=subprocess.PIPE) + self.state = STATE_SAVEDEFCONFIG + + def update_defconfig(self): + """Update the input defconfig and go back to the idle state.""" + orig_defconfig = os.path.join('configs', self.defconfig) + new_defconfig = os.path.join(self.build_dir, 'defconfig') + updated = not filecmp.cmp(orig_defconfig, new_defconfig) + + if updated: + self.log.append( + self.col.build(self.col.BLUE, 'defconfig updated', bright=True)) + + if not self.args.dry_run and updated: + shutil.move(new_defconfig, orig_defconfig) + self.finish(True) + + def finish(self, success): + """Display log along with progress and go to the idle state. + + Args: + success (bool): Should be True when the defconfig was processed + successfully, or False when it fails. + """ + # output at least 30 characters to hide the "* defconfigs out of *". + name = self.defconfig[:-len('_defconfig')] + if self.log: + + # Put the first log line on the first line + log = name.ljust(20) + ' ' + self.log[0] + + if len(self.log) > 1: + log += '\n' + '\n'.join([' ' + s for s in self.log[1:]]) + # Some threads are running in parallel. + # Print log atomically to not mix up logs from different threads. + print(log, file=(sys.stdout if success else sys.stderr)) + + if not success: + if self.args.exit_on_error: + sys.exit('Exit on error.') + # If --exit-on-error flag is not set, skip this board and continue. + # Record the failed board. + self.failed_boards.add(name) + + self.progress.inc(success) + self.progress.show() + self.state = STATE_IDLE + + def get_failed_boards(self): + """Returns a set of failed boards (defconfigs) in this slot. + """ + return self.failed_boards + +class Slots: + + """Controller of the array of subprocess slots.""" + + def __init__(self, toolchains, args, progress, reference_src_dir, db_queue, + col): + """Create a new slots controller. + + Args: + toolchains (Toolchains): Toolchains object containing toolchains + args (Namespace): Program arguments + progress (Progress): A progress indicator. + reference_src_dir (str): Determine the true starting config state + from this source tree (None for none) + db_queue (Queue): output queue to write config info for the database + col (terminal.Color): Colour object + """ + self.args = args + self.slots = [] + self.progress = progress + self.col = col + devnull = subprocess.DEVNULL + make_cmd = get_make_cmd() + for _ in range(args.jobs): + self.slots.append(Slot(toolchains, args, progress, devnull, + make_cmd, reference_src_dir, db_queue, col)) + + def add(self, defconfig): + """Add a new subprocess if a vacant slot is found. + + Args: + defconfig (str): defconfig name to be put into. + + Returns: + Return True on success or False on failure + """ + for slot in self.slots: + if slot.add(defconfig): + return True + return False + + def available(self): + """Check if there is a vacant slot. + + Returns: + Return True if at lease one vacant slot is found, False otherwise. + """ + for slot in self.slots: + if slot.poll(): + return True + return False + + def empty(self): + """Check if all slots are vacant. + + Returns: + Return True if all the slots are vacant, False otherwise. + """ + ret = True + for slot in self.slots: + if not slot.poll(): + ret = False + return ret + + def write_failed_boards(self): + """Show the results of processing""" + boards = set() + + for slot in self.slots: + boards |= slot.get_failed_boards() + + if boards: + boards = '\n'.join(sorted(boards)) + '\n' + write_file(FAILED_LIST, boards) + + +class ReferenceSource: + + """Reference source against which original configs should be parsed.""" + + def __init__(self, commit): + """Create a reference source directory based on a specified commit. + + Args: + commit: commit to git-clone + """ + self.src_dir = tempfile.mkdtemp() + print('Cloning git repo to a separate work directory...') + subprocess.check_output(['git', 'clone', os.getcwd(), '.'], + cwd=self.src_dir) + rev = subprocess.check_output(['git', 'rev-parse', '--short', + commit]).strip() + print(f"Checkout '{rev}' to build the original autoconf.mk.") + subprocess.check_output(['git', 'checkout', commit], + stderr=subprocess.STDOUT, cwd=self.src_dir) + + def __del__(self): + """Delete the reference source directory + + This function makes sure the temporary directory is cleaned away + even if Python suddenly dies due to error. It should be done in here + because it is guaranteed the destructor is always invoked when the + instance of the class gets unreferenced. + """ + shutil.rmtree(self.src_dir) + + def get_dir(self): + """Return the absolute path to the reference source directory.""" + + return self.src_dir + +def move_config(toolchains, args, db_queue, col): + """Build database or sync config options to defconfig files. + + Args: + toolchains (Toolchains): Toolchains to use + args (Namespace): Program arguments + db_queue (Queue): Queue for database updates + col (terminal.Color): Colour object + + Returns: + Progress: Progress indicator + """ + if args.git_ref: + reference_src = ReferenceSource(args.git_ref) + reference_src_dir = reference_src.get_dir() + else: + reference_src_dir = None + + if args.defconfigs: + defconfigs = get_matched_defconfigs(args.defconfigs) + else: + defconfigs = get_all_defconfigs() + + progress = Progress(col, len(defconfigs)) + slots = Slots(toolchains, args, progress, reference_src_dir, db_queue, col) + + # Main loop to process defconfig files: + # Add a new subprocess into a vacant slot. + # Sleep if there is no available slot. + for defconfig in defconfigs: + while not slots.add(defconfig): + while not slots.available(): + # No available slot: sleep for a while + time.sleep(SLEEP_TIME) + + # wait until all the subprocesses finish + while not slots.empty(): + time.sleep(SLEEP_TIME) + + slots.write_failed_boards() + return progress + +def find_kconfig_rules(kconf, config, imply_config): + """Check whether a config has a 'select' or 'imply' keyword + + Args: + kconf (Kconfiglib.Kconfig): Kconfig object + config (str): Name of config to check (without CONFIG_ prefix) + imply_config (str): Implying config (without CONFIG_ prefix) which may + or may not have an 'imply' for 'config') + + Returns: + Symbol object for 'config' if found, else None + """ + sym = kconf.syms.get(imply_config) + if sym: + for sel, _ in (sym.selects + sym.implies): + if sel.name == config: + return sym + return None + +def check_imply_rule(kconf, config, imply_config): + """Check if we can add an 'imply' option + + This finds imply_config in the Kconfig and looks to see if it is possible + to add an 'imply' for 'config' to that part of the Kconfig. + + Args: + kconf (Kconfiglib.Kconfig): Kconfig object + config (str): Name of config to check (without CONFIG_ prefix) + imply_config (str): Implying config (without CONFIG_ prefix) which may + or may not have an 'imply' for 'config') + + Returns: + tuple: + str: filename of Kconfig file containing imply_config, or None if + none + int: line number within the Kconfig file, or 0 if none + str: message indicating the result + """ + sym = kconf.syms.get(imply_config) + if not sym: + return 'cannot find sym' + nodes = sym.nodes + if len(nodes) != 1: + return f'{len(nodes)} locations' + node = nodes[0] + fname, linenum = node.filename, node.linenr + cwd = os.getcwd() + if cwd and fname.startswith(cwd): + fname = fname[len(cwd) + 1:] + file_line = f' at {fname}:{linenum}' + data = read_file(fname) + if data[linenum - 1] != f'config {imply_config}': + return None, 0, f'bad sym format {data[linenum]}{file_line})' + return fname, linenum, f'adding{file_line}' + +def add_imply_rule(config, fname, linenum): + """Add a new 'imply' option to a Kconfig + + Args: + config (str): config option to add an imply for (without CONFIG_ prefix) + fname (str): Kconfig filename to update + linenum (int): Line number to place the 'imply' before + + Returns: + Message indicating the result + """ + file_line = f' at {fname}:{linenum}' + data = read_file(fname) + linenum -= 1 + + for offset, line in enumerate(data[linenum:]): + if line.strip().startswith('help') or not line: + data.insert(linenum + offset, f'\timply {config}') + write_file(fname, data) + return f'added{file_line}' + + return 'could not insert%s' + +(IMPLY_MIN_2, IMPLY_TARGET, IMPLY_CMD, IMPLY_NON_ARCH_BOARD) = ( + 1, 2, 4, 8) + +IMPLY_FLAGS = { + 'min2': [IMPLY_MIN_2, 'Show options which imply >2 boards (normally >5)'], + 'target': [IMPLY_TARGET, 'Allow CONFIG_TARGET_... options to imply'], + 'cmd': [IMPLY_CMD, 'Allow CONFIG_CMD_... to imply'], + 'non-arch-board': [ + IMPLY_NON_ARCH_BOARD, + 'Allow Kconfig options outside arch/ and /board/ to imply'], +} + + +def read_database(): + """Read in the config database + + Returns: + tuple: + set of all config options seen (each a str) + set of all defconfigs seen (each a str) + dict of configs for each defconfig: + key: defconfig name, e.g. "MPC8548CDS_legacy_defconfig" + value: dict: + key: CONFIG option + value: Value of option + dict of defconfigs for each config: + key: CONFIG option + value: set of boards using that option + + """ + configs = {} + + # key is defconfig name, value is dict of (CONFIG_xxx, value) + config_db = {} + + # Set of all config options we have seen + all_configs = set() + + # Set of all defconfigs we have seen + all_defconfigs = set() + + defconfig_db = collections.defaultdict(set) + for line in read_file(CONFIG_DATABASE): + line = line.rstrip() + if not line: # Separator between defconfigs + config_db[defconfig] = configs + all_defconfigs.add(defconfig) + configs = {} + elif line[0] == ' ': # CONFIG line + config, value = line.strip().split('=', 1) + configs[config] = value + defconfig_db[config].add(defconfig) + all_configs.add(config) + else: # New defconfig + defconfig = line + + return all_configs, all_defconfigs, config_db, defconfig_db + + +def do_imply_config(config_list, add_imply, imply_flags, skip_added, + check_kconfig=True, find_superset=False): + """Find CONFIG options which imply those in the list + + Some CONFIG options can be implied by others and this can help to reduce + the size of the defconfig files. For example, CONFIG_X86 implies + CONFIG_CMD_IRQ, so we can put 'imply CMD_IRQ' under 'config X86' and + all x86 boards will have that option, avoiding adding CONFIG_CMD_IRQ to + each of the x86 defconfig files. + + This function uses the qconfig database to find such options. It + displays a list of things that could possibly imply those in the list. + The algorithm ignores any that start with CONFIG_TARGET since these + typically refer to only a few defconfigs (often one). It also does not + display a config with less than 5 defconfigs. + + The algorithm works using sets. For each target config in config_list: + - Get the set 'defconfigs' which use that target config + - For each config (from a list of all configs): + - Get the set 'imply_defconfig' of defconfigs which use that config + - + - If imply_defconfigs contains anything not in defconfigs then + this config does not imply the target config + + Params: + config_list: List of CONFIG options to check (each a string) + add_imply: Automatically add an 'imply' for each config. + imply_flags: Flags which control which implying configs are allowed + (IMPLY_...) + skip_added: Don't show options which already have an imply added. + check_kconfig: Check if implied symbols already have an 'imply' or + 'select' for the target config, and show this information if so. + find_superset: True to look for configs which are a superset of those + already found. So for example if CONFIG_EXYNOS5 implies an option, + but CONFIG_EXYNOS covers a larger set of defconfigs and also + implies that option, this will drop the former in favour of the + latter. In practice this option has not proved very used. + + Note the terminoloy: + config - a CONFIG_XXX options (a string, e.g. 'CONFIG_CMD_EEPROM') + defconfig - a defconfig file (a string, e.g. 'configs/snow_defconfig') + """ + kconf = KconfigScanner().conf if check_kconfig else None + if add_imply and add_imply != 'all': + add_imply = add_imply.split(',') + + all_configs, all_defconfigs, _, defconfig_db = read_database() + + # Work through each target config option in turn, independently + for config in config_list: + defconfigs = defconfig_db.get(config) + if not defconfigs: + print(f'{config} not found in any defconfig') + continue + + # Get the set of defconfigs without this one (since a config cannot + # imply itself) + non_defconfigs = all_defconfigs - defconfigs + num_defconfigs = len(defconfigs) + print(f'{config} found in {num_defconfigs}/{len(all_configs)} defconfigs') + + # This will hold the results: key=config, value=defconfigs containing it + imply_configs = {} + rest_configs = all_configs - set([config]) + + # Look at every possible config, except the target one + for imply_config in rest_configs: + if 'ERRATUM' in imply_config: + continue + if not imply_flags & IMPLY_CMD: + if 'CONFIG_CMD' in imply_config: + continue + if not imply_flags & IMPLY_TARGET: + if 'CONFIG_TARGET' in imply_config: + continue + + # Find set of defconfigs that have this config + imply_defconfig = defconfig_db[imply_config] + + # Get the intersection of this with defconfigs containing the + # target config + common_defconfigs = imply_defconfig & defconfigs + + # Get the set of defconfigs containing this config which DO NOT + # also contain the taret config. If this set is non-empty it means + # that this config affects other defconfigs as well as (possibly) + # the ones affected by the target config. This means it implies + # things we don't want to imply. + not_common_defconfigs = imply_defconfig & non_defconfigs + if not_common_defconfigs: + continue + + # If there are common defconfigs, imply_config may be useful + if common_defconfigs: + skip = False + if find_superset: + for prev in list(imply_configs.keys()): + prev_count = len(imply_configs[prev]) + count = len(common_defconfigs) + if (prev_count > count and + (imply_configs[prev] & common_defconfigs == + common_defconfigs)): + # skip imply_config because prev is a superset + skip = True + break + if count > prev_count: + # delete prev because imply_config is a superset + del imply_configs[prev] + if not skip: + imply_configs[imply_config] = common_defconfigs + + # Now we have a dict imply_configs of configs which imply each config + # The value of each dict item is the set of defconfigs containing that + # config. Rank them so that we print the configs that imply the largest + # number of defconfigs first. + ranked_iconfigs = sorted(imply_configs, + key=lambda k: len(imply_configs[k]), reverse=True) + kconfig_info = '' + cwd = os.getcwd() + add_list = collections.defaultdict(list) + for iconfig in ranked_iconfigs: + num_common = len(imply_configs[iconfig]) + + # Don't bother if there are less than 5 defconfigs affected. + if num_common < (2 if imply_flags & IMPLY_MIN_2 else 5): + continue + missing = defconfigs - imply_configs[iconfig] + missing_str = ', '.join(missing) if missing else 'all' + missing_str = '' + show = True + if kconf: + sym = find_kconfig_rules(kconf, config[CONFIG_LEN:], + iconfig[CONFIG_LEN:]) + kconfig_info = '' + if sym: + nodes = sym.nodes + if len(nodes) == 1: + fname, linenum = nodes[0].filename, nodes[0].linenr + if cwd and fname.startswith(cwd): + fname = fname[len(cwd) + 1:] + kconfig_info = f'{fname}:{linenum}' + if skip_added: + show = False + else: + sym = kconf.syms.get(iconfig[CONFIG_LEN:]) + fname = '' + if sym: + nodes = sym.nodes + if len(nodes) == 1: + fname, linenum = nodes[0].filename, nodes[0].linenr + if cwd and fname.startswith(cwd): + fname = fname[len(cwd) + 1:] + in_arch_board = not sym or (fname.startswith('arch') or + fname.startswith('board')) + if (not in_arch_board and + not imply_flags & IMPLY_NON_ARCH_BOARD): + continue + + if add_imply and (add_imply == 'all' or + iconfig in add_imply): + fname, linenum, kconfig_info = (check_imply_rule(kconf, + config[CONFIG_LEN:], iconfig[CONFIG_LEN:])) + if fname: + add_list[fname].append(linenum) + + if show and kconfig_info != 'skip': + print(f'{num_common:5d} : ' + f'{iconfig.ljust(30):-30s}{kconfig_info:-25s} {missing_str}') + + # Having collected a list of things to add, now we add them. We process + # each file from the largest line number to the smallest so that + # earlier additions do not affect our line numbers. E.g. if we added an + # imply at line 20 it would change the position of each line after + # that. + for fname, linenums in add_list.items(): + for linenum in sorted(linenums, reverse=True): + add_imply_rule(config[CONFIG_LEN:], fname, linenum) + +def defconfig_matches(configs, re_match): + """Check if any CONFIG option matches a regex + + The match must be complete, i.e. from the start to end of the CONFIG option. + + Args: + configs (dict): Dict of CONFIG options: + key: CONFIG option + value: Value of option + re_match (re.Pattern): Match to check + + Returns: + bool: True if any CONFIG matches the regex + """ + for cfg in configs: + if re_match.fullmatch(cfg): + return True + return False + +def do_find_config(config_list): + """Find boards with a given combination of CONFIGs + + Params: + config_list: List of CONFIG options to check (each a regex consisting + of a config option, with or without a CONFIG_ prefix. If an option + is preceded by a tilde (~) then it must be false, otherwise it must + be true) + """ + _, all_defconfigs, config_db, _ = read_database() + + # Start with all defconfigs + out = all_defconfigs + + # Work through each config in turn + for item in config_list: + # Get the real config name and whether we want this config or not + cfg = item + want = True + if cfg[0] == '~': + want = False + cfg = cfg[1:] + + # Search everything that is still in the running. If it has a config + # that we want, or doesn't have one that we don't, add it into the + # running for the next stage + in_list = out + out = set() + re_match = re.compile(cfg) + for defc in in_list: + has_cfg = defconfig_matches(config_db[defc], re_match) + if has_cfg == want: + out.add(defc) + print(f'{len(out)} matches') + print(' '.join(item.split('_defconfig')[0] for item in out)) + + +def prefix_config(cfg): + """Prefix a config with CONFIG_ if needed + + This handles ~ operator, which indicates that the CONFIG should be disabled + + >>> prefix_config('FRED') + 'CONFIG_FRED' + >>> prefix_config('CONFIG_FRED') + 'CONFIG_FRED' + >>> prefix_config('~FRED') + '~CONFIG_FRED' + >>> prefix_config('~CONFIG_FRED') + '~CONFIG_FRED' + >>> prefix_config('A123') + 'CONFIG_A123' + """ + oper = '' + if cfg[0] == '~': + oper = cfg[0] + cfg = cfg[1:] + if not cfg.startswith('CONFIG_'): + cfg = 'CONFIG_' + cfg + return oper + cfg + + +RE_MK_CONFIGS = re.compile(r'CONFIG_(\$\(SPL_(?:TPL_)?\))?([A-Za-z0-9_]*)') +RE_IFDEF = re.compile(r'(ifdef|ifndef)') +RE_C_CONFIGS = re.compile(r'CONFIG_([A-Za-z0-9_]*)') +RE_CONFIG_IS = re.compile(r'CONFIG_IS_ENABLED\(([A-Za-z0-9_]*)\)') + +class ConfigUse: + def __init__(self, cfg, is_spl, fname, rest): + self.cfg = cfg + self.is_spl = is_spl + self.fname = fname + self.rest = rest + + def __hash__(self): + return hash((self.cfg, self.is_spl)) + +def scan_makefiles(fnames): + """Scan Makefiles looking for Kconfig options + + Looks for uses of CONFIG options in Makefiles + + Args: + fnames (list of tuple): + str: Makefile filename where the option was found + str: Line of the Makefile + + Returns: + tuple: + dict: all_uses + key (ConfigUse): object + value (list of str): matching lines + dict: Uses by filename + key (str): filename + value (set of ConfigUse): uses in that filename + + >>> RE_MK_CONFIGS.search('CONFIG_FRED').groups() + (None, 'FRED') + >>> RE_MK_CONFIGS.search('CONFIG_$(SPL_)MARY').groups() + ('$(SPL_)', 'MARY') + >>> RE_MK_CONFIGS.search('CONFIG_$(SPL_TPL_)MARY').groups() + ('$(SPL_TPL_)', 'MARY') + """ + all_uses = collections.defaultdict(list) + fname_uses = {} + for fname, rest in fnames: + m_iter = RE_MK_CONFIGS.finditer(rest) + for mat in m_iter: + real_opt = mat.group(2) + if real_opt == '': + continue + is_spl = False + if mat.group(1): + is_spl = True + use = ConfigUse(real_opt, is_spl, fname, rest) + if fname not in fname_uses: + fname_uses[fname] = set() + fname_uses[fname].add(use) + all_uses[use].append(rest) + return all_uses, fname_uses + + +def scan_src_files(fnames): + """Scan source files (other than Makefiles) looking for Kconfig options + + Looks for uses of CONFIG options + + Args: + fnames (list of tuple): + str: Makefile filename where the option was found + str: Line of the Makefile + + Returns: + tuple: + dict: all_uses + key (ConfigUse): object + value (list of str): matching lines + dict: Uses by filename + key (str): filename + value (set of ConfigUse): uses in that filename + + >>> RE_C_CONFIGS.search('CONFIG_FRED').groups() + ('FRED',) + >>> RE_CONFIG_IS.search('CONFIG_IS_ENABLED(MARY)').groups() + ('MARY',) + >>> RE_CONFIG_IS.search('#if CONFIG_IS_ENABLED(OF_PLATDATA)').groups() + ('OF_PLATDATA',) + """ + fname = None + rest = None + + def add_uses(m_iter, is_spl): + for mat in m_iter: + real_opt = mat.group(1) + if real_opt == '': + continue + use = ConfigUse(real_opt, is_spl, fname, rest) + if fname not in fname_uses: + fname_uses[fname] = set() + fname_uses[fname].add(use) + all_uses[use].append(rest) + + all_uses = collections.defaultdict(list) + fname_uses = {} + for fname, rest in fnames: + m_iter = RE_C_CONFIGS.finditer(rest) + add_uses(m_iter, False) + + m_iter2 = RE_CONFIG_IS.finditer(rest) + add_uses(m_iter2, True) + + return all_uses, fname_uses + + +MODE_NORMAL, MODE_SPL, MODE_PROPER = range(3) + +def do_scan_source(path, do_update): + """Scan the source tree for Kconfig inconsistencies + + Args: + path (str): Path to source tree + do_update (bool) : True to write to scripts/kconf_... files + """ + def is_not_proper(name): + for prefix in SPL_PREFIXES: + if name.startswith(prefix): + return name[len(prefix):] + return False + + def check_not_found(all_uses, spl_mode): + """Check for Kconfig options mentioned in the source but not in Kconfig + + Args: + all_uses (dict): + key (ConfigUse): object + value (list of str): matching lines + spl_mode (int): If MODE_SPL, look at source code which implies + an SPL_ option, but for which there is none; + for MOD_PROPER, look at source code which implies a Proper + option (i.e. use of CONFIG_IS_ENABLED() or $(SPL_) or + $(SPL_TPL_) but for which there none; + if MODE_NORMAL, ignore SPL + + Returns: + dict: + key (str): CONFIG name (without 'CONFIG_' prefix + value (list of ConfigUse): List of uses of this CONFIG + """ + # Make sure we know about all the options + not_found = collections.defaultdict(list) + for use, _ in all_uses.items(): + name = use.cfg + if name in IGNORE_SYMS: + continue + check = True + + if spl_mode == MODE_SPL: + check = use.is_spl + + # If it is an SPL symbol, try prepending all SPL_ prefixes to + # find at least one SPL symbol + if use.is_spl: + for prefix in SPL_PREFIXES: + try_name = prefix + name + sym = kconf.syms.get(try_name) + if sym: + break + if not sym: + not_found[f'SPL_{name}'].append(use) + continue + elif spl_mode == MODE_PROPER: + # Try to find the Proper version of this symbol, i.e. without + # the SPL_ prefix + proper_name = is_not_proper(name) + if proper_name: + name = proper_name + elif not use.is_spl: + check = False + else: # MODE_NORMAL + sym = kconf.syms.get(name) + if not sym: + proper_name = is_not_proper(name) + if proper_name: + name = proper_name + sym = kconf.syms.get(name) + if not sym: + for prefix in SPL_PREFIXES: + try_name = prefix + name + sym = kconf.syms.get(try_name) + if sym: + break + if not sym: + not_found[name].append(use) + continue + + sym = kconf.syms.get(name) + if not sym and check: + not_found[name].append(use) + return not_found + + def show_uses(uses): + """Show a list of uses along with their filename and code snippet + + Args: + uses (dict): + key (str): CONFIG name (without 'CONFIG_' prefix + value (list of ConfigUse): List of uses of this CONFIG + """ + for name in sorted(uses): + print(f'{name}: ', end='') + for i, use in enumerate(uses[name]): + print(f'{" " if i else ""}{use.fname}: {use.rest.strip()}') + + + print('Scanning Kconfig') + kconf = KconfigScanner().conf + print(f'Scanning source in {path}') + args = ['git', 'grep', '-E', r'IS_ENABLED|\bCONFIG'] + with subprocess.Popen(args, stdout=subprocess.PIPE) as proc: + out, _ = proc.communicate() + lines = out.splitlines() + re_fname = re.compile('^([^:]*):(.*)') + src_list = [] + mk_list = [] + for line in lines: + linestr = line.decode('utf-8') + m_fname = re_fname.search(linestr) + if not m_fname: + continue + fname, rest = m_fname.groups() + dirname, leaf = os.path.split(fname) + root, ext = os.path.splitext(leaf) + if ext == '.autoconf': + pass + elif ext in ['.c', '.h', '.S', '.lds', '.dts', '.dtsi', '.asl', '.cfg', + '.env', '.tmpl']: + src_list.append([fname, rest]) + elif 'Makefile' in root or ext == '.mk': + mk_list.append([fname, rest]) + elif ext in ['.yml', '.sh', '.py', '.awk', '.pl', '.rst', '', '.sed']: + pass + elif 'Kconfig' in root or 'Kbuild' in root: + pass + elif 'README' in root: + pass + elif dirname in ['configs']: + pass + elif dirname.startswith('doc') or dirname.startswith('scripts/kconfig'): + pass + else: + print(f'Not sure how to handle file {fname}') + + # Scan the Makefiles + all_uses, _ = scan_makefiles(mk_list) + + spl_not_found = set() + proper_not_found = set() + + # Make sure we know about all the options + print('\nCONFIG options present in Makefiles but not Kconfig:') + not_found = check_not_found(all_uses, MODE_NORMAL) + show_uses(not_found) + + print('\nCONFIG options present in Makefiles but not Kconfig (SPL):') + not_found = check_not_found(all_uses, MODE_SPL) + show_uses(not_found) + spl_not_found |= {is_not_proper(key) or key for key in not_found.keys()} + + print('\nCONFIG options used as Proper in Makefiles but without a non-SPL_ variant:') + not_found = check_not_found(all_uses, MODE_PROPER) + show_uses(not_found) + proper_not_found |= {not_found.keys()} + + # Scan the source code + all_uses, _ = scan_src_files(src_list) + + # Make sure we know about all the options + print('\nCONFIG options present in source but not Kconfig:') + not_found = check_not_found(all_uses, MODE_NORMAL) + show_uses(not_found) + + print('\nCONFIG options present in source but not Kconfig (SPL):') + not_found = check_not_found(all_uses, MODE_SPL) + show_uses(not_found) + spl_not_found |= {is_not_proper(key) or key for key in not_found.keys()} + + print('\nCONFIG options used as Proper in source but without a non-SPL_ variant:') + not_found = check_not_found(all_uses, MODE_PROPER) + show_uses(not_found) + proper_not_found |= {not_found.keys()} + + print('\nCONFIG options used as SPL but without an SPL_ variant:') + for item in sorted(spl_not_found): + print(f' {item}') + + print('\nCONFIG options used as Proper but without a non-SPL_ variant:') + for item in sorted(proper_not_found): + print(f' {item}') + + # Write out the updated information + if do_update: + with open(os.path.join(path, 'scripts', 'conf_nospl'), 'w', + encoding='utf-8') as out: + print('# These options should not be enabled in SPL builds\n', + file=out) + for item in sorted(spl_not_found): + print(item, file=out) + with open(os.path.join(path, 'scripts', 'conf_noproper'), 'w', + encoding='utf-8') as out: + print('# These options should not be enabled in Proper builds\n', + file=out) + for item in sorted(proper_not_found): + print(item, file=out) + + +def main(): + try: + cpu_count = multiprocessing.cpu_count() + except NotImplementedError: + cpu_count = 1 + + epilog = '''Move config options from headers to defconfig files. See +doc/develop/moveconfig.rst for documentation.''' + + parser = ArgumentParser(epilog=epilog) + # Add arguments here + parser.add_argument('-a', '--add-imply', type=str, default='', + help='comma-separated list of CONFIG options to add ' + "an 'imply' statement to for the CONFIG in -i") + parser.add_argument('-A', '--skip-added', action='store_true', default=False, + help="don't show options which are already marked as " + 'implying others') + parser.add_argument('-b', '--build-db', action='store_true', default=False, + help='build a CONFIG database') + parser.add_argument('-C', '--commit', action='store_true', default=False, + help='Create a git commit for the operation') + parser.add_argument('--nocolour', action='store_true', default=False, + help="don't display the log in colour") + parser.add_argument('-d', '--defconfigs', type=str, + help='a file containing a list of defconfigs to move, ' + "one per line (for example 'snow_defconfig') " + "or '-' to read from stdin") + parser.add_argument('-e', '--exit-on-error', action='store_true', + default=False, + help='exit immediately on any error') + parser.add_argument('-f', '--find', action='store_true', default=False, + help='Find boards with a given config combination') + parser.add_argument('-i', '--imply', action='store_true', default=False, + help='find options which imply others') + parser.add_argument('-I', '--imply-flags', type=str, default='', + help="control the -i option ('help' for help") + parser.add_argument('-j', '--jobs', type=int, default=cpu_count, + help='the number of jobs to run simultaneously') + parser.add_argument('-n', '--dry-run', action='store_true', default=False, + help='perform a trial run (show log with no changes)') + parser.add_argument('-r', '--git-ref', type=str, + help='the git ref to clone for building the autoconf.mk') + parser.add_argument('-s', '--force-sync', action='store_true', default=False, + help='force sync by savedefconfig') + parser.add_argument('-S', '--spl', action='store_true', default=False, + help='parse config options defined for SPL build') + parser.add_argument('--scan-source', action='store_true', default=False, + help='scan source for uses of CONFIG options') + parser.add_argument('-t', '--test', action='store_true', default=False, + help='run unit tests') + parser.add_argument('-y', '--yes', action='store_true', default=False, + help="respond 'yes' to any prompts") + parser.add_argument('-u', '--update', action='store_true', default=False, + help="update scripts/ files (use with --scan-source)") + parser.add_argument('-v', '--verbose', action='store_true', default=False, + help='show any build errors as boards are built') + parser.add_argument('configs', nargs='*') + + args = parser.parse_args() + + if args.test: + sys.argv = [sys.argv[0]] + fail, _ = doctest.testmod() + if fail: + return 1 + unittest.main() + + col = terminal.Color(terminal.COLOR_NEVER if args.nocolour + else terminal.COLOR_IF_TERMINAL) + + if args.scan_source: + do_scan_source(os.getcwd(), args.update) + return 0 + + if not any((args.force_sync, args.build_db, args.imply, args.find)): + parser.print_usage() + sys.exit(1) + + # prefix the option name with CONFIG_ if missing + configs = [prefix_config(cfg) for cfg in args.configs] + + check_top_directory() + + if args.imply: + imply_flags = 0 + if args.imply_flags == 'all': + imply_flags = -1 + + elif args.imply_flags: + for flag in args.imply_flags.split(','): + bad = flag not in IMPLY_FLAGS + if bad: + print(f"Invalid flag '{flag}'") + if flag == 'help' or bad: + print("Imply flags: (separate with ',')") + for name, info in IMPLY_FLAGS.items(): + print(f' {name:-15s}: {info[1]}') + parser.print_usage() + sys.exit(1) + imply_flags |= IMPLY_FLAGS[flag][0] + + do_imply_config(configs, args.add_imply, imply_flags, args.skip_added) + return 0 + + if args.find: + do_find_config(configs) + return 0 + + # We are either building the database or forcing a sync of defconfigs + config_db = {} + db_queue = queue.Queue() + dbt = DatabaseThread(config_db, db_queue) + dbt.daemon = True + dbt.start() + + check_clean_directory() + bsettings.setup('') + toolchains = toolchain.Toolchains() + toolchains.GetSettings() + toolchains.Scan(verbose=False) + progress = move_config(toolchains, args, db_queue, col) + db_queue.join() + + if args.commit: + subprocess.call(['git', 'add', '-u']) + if configs: + msg = 'Convert %s %sto Kconfig' % (configs[0], + 'et al ' if len(configs) > 1 else '') + msg += ('\n\nThis converts the following to Kconfig:\n %s\n' % + '\n '.join(configs)) + else: + msg = 'configs: Resync with savedefconfig' + msg += '\n\nRsync all defconfig files using moveconfig.py' + subprocess.call(['git', 'commit', '-s', '-m', msg]) + + failed = progress.total - progress.good + failure = f'{failed} failed, ' if failed else '' + if args.build_db: + with open(CONFIG_DATABASE, 'w', encoding='utf-8') as outf: + for defconfig, configs in config_db.items(): + outf.write(f'{defconfig}\n') + for config in sorted(configs.keys()): + outf.write(f' {config}={configs[config]}\n') + outf.write('\n') + print(col.build( + col.RED if failed else col.GREEN, + f'{failure}{len(config_db)} boards written to {CONFIG_DATABASE}')) + else: + if failed: + print(col.build(col.RED, f'{failure}see {FAILED_LIST}', True)) + else: + # Add enough spaces to overwrite the progress indicator + print(col.build( + col.GREEN, f'{progress.total} processed ', bright=True)) + + return 0 + + +if __name__ == '__main__': + sys.exit(main()) -- cgit v1.1 From 519637929b95d780d731bad5bbaeadfff727e951 Mon Sep 17 00:00:00 2001 From: Simon Glass Date: Sat, 23 Sep 2023 13:44:15 -0600 Subject: qconfig: Rename the database file Use qconfig.db as the new name, to reflect the tool's purpose. Signed-off-by: Simon Glass --- .gitignore | 4 ++-- tools/qconfig.py | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.gitignore b/.gitignore index 9697f00..aa01604 100644 --- a/.gitignore +++ b/.gitignore @@ -107,5 +107,5 @@ __pycache__ /pylint.cur /pylint.out/ -# moveconfig database -/moveconfig.db +# qconfig database +/qconfig.db diff --git a/tools/qconfig.py b/tools/qconfig.py index dd55a69..04118d9 100755 --- a/tools/qconfig.py +++ b/tools/qconfig.py @@ -44,8 +44,8 @@ STATE_AUTOCONF = 2 STATE_SAVEDEFCONFIG = 3 AUTO_CONF_PATH = 'include/config/auto.conf' -CONFIG_DATABASE = 'moveconfig.db' -FAILED_LIST = 'moveconfig.failed' +CONFIG_DATABASE = 'qconfig.db' +FAILED_LIST = 'qconfig.failed' CONFIG_LEN = len('CONFIG_') -- cgit v1.1 From 4840b71bb009711564e20f9695b92950c3f73e42 Mon Sep 17 00:00:00 2001 From: Simon Glass Date: Sat, 23 Sep 2023 13:44:16 -0600 Subject: qconfig: Update the documentation Update qconfig's documentation to better reflect its new purpose in life. Signed-off-by: Simon Glass --- doc/develop/index.rst | 2 +- doc/develop/moveconfig.rst | 302 --------------------------------------------- doc/develop/qconfig.rst | 234 +++++++++++++++++++++++++++++++++++ 3 files changed, 235 insertions(+), 303 deletions(-) delete mode 100644 doc/develop/moveconfig.rst create mode 100644 doc/develop/qconfig.rst diff --git a/doc/develop/index.rst b/doc/develop/index.rst index 0d12484..003cdfc 100644 --- a/doc/develop/index.rst +++ b/doc/develop/index.rst @@ -88,7 +88,7 @@ Refactoring checkpatch coccinelle - moveconfig + qconfig Code quality ------------ diff --git a/doc/develop/moveconfig.rst b/doc/develop/moveconfig.rst deleted file mode 100644 index ad8596e..0000000 --- a/doc/develop/moveconfig.rst +++ /dev/null @@ -1,302 +0,0 @@ -.. SPDX-License-Identifier: GPL-2.0+ - -moveconfig - Migrating and querying CONFIG options -================================================== - -Since Kconfig was introduced to U-Boot, we have worked on moving -config options from headers to Kconfig (defconfig). - -This tool intends to help this tremendous work. - -Installing ----------- - -You may need to install 'python3-asteval' for the 'asteval' module. - -Usage ------ - -First, you must edit the Kconfig to add the menu entries for the configs -you are moving. - -Then run this tool giving CONFIG names you want to move. -For example, if you want to move CONFIG_CMD_USB and CONFIG_TEXT_BASE, -simply type as follows:: - - $ tools/moveconfig.py CONFIG_CMD_USB CONFIG_TEXT_BASE - -The tool walks through all the defconfig files and move the given CONFIGs. - -The log is also displayed on the terminal. - -The log is printed for each defconfig as follows:: - - - - - - ... - -`` is the name of the defconfig. - -`` shows what the tool did for that defconfig. -It looks like one of the following: - - - Move 'CONFIG\_... ' - This config option was moved to the defconfig - - - CONFIG\_... is not defined in Kconfig. Do nothing. - The entry for this CONFIG was not found in Kconfig. The option is not - defined in the config header, either. So, this case can be just skipped. - - - CONFIG\_... is not defined in Kconfig (suspicious). Do nothing. - This option is defined in the config header, but its entry was not found - in Kconfig. - There are two common cases: - - - You forgot to create an entry for the CONFIG before running - this tool, or made a typo in a CONFIG passed to this tool. - - The entry was hidden due to unmet 'depends on'. - - The tool does not know if the result is reasonable, so please check it - manually. - - - 'CONFIG\_...' is the same as the define in Kconfig. Do nothing. - The define in the config header matched the one in Kconfig. - We do not need to touch it. - - - Compiler is missing. Do nothing. - The compiler specified for this architecture was not found - in your PATH environment. - (If -e option is passed, the tool exits immediately.) - - - Failed to process. - An error occurred during processing this defconfig. Skipped. - (If -e option is passed, the tool exits immediately on error.) - -Finally, you will be asked, Clean up headers? [y/n]: - -If you say 'y' here, the unnecessary config defines are removed -from the config headers (include/configs/\*.h). -It just uses the regex method, so you should not rely on it. -Just in case, please do 'git diff' to see what happened. - - -How does it work? ------------------ - -This tool runs configuration and builds include/autoconf.mk for every -defconfig. The config options defined in Kconfig appear in the .config -file (unless they are hidden because of unmet dependency.) -On the other hand, the config options defined by board headers are seen -in include/autoconf.mk. The tool looks for the specified options in both -of them to decide the appropriate action for the options. If the given -config option is found in the .config, but its value does not match the -one from the board header, the config option in the .config is replaced -with the define in the board header. Then, the .config is synced by -"make savedefconfig" and the defconfig is updated with it. - -For faster processing, this tool handles multi-threading. It creates -separate build directories where the out-of-tree build is run. The -temporary build directories are automatically created and deleted as -needed. The number of threads are chosen based on the number of the CPU -cores of your system although you can change it via -j (--jobs) option. - - -Toolchains ----------- - -Appropriate toolchain are necessary to generate include/autoconf.mk -for all the architectures supported by U-Boot. Most of them are available -at the kernel.org site, some are not provided by kernel.org. This tool uses -the same tools as buildman, so see that tool for setup (e.g. --fetch-arch). - - -Tips and trips --------------- - -To sync only X86 defconfigs:: - - ./tools/moveconfig.py -s -d <(grep -l X86 configs/*) - -or:: - - grep -l X86 configs/* | ./tools/moveconfig.py -s -d - - -To process CONFIG_CMD_FPGAD only for a subset of configs based on path match:: - - ls configs/{hrcon*,iocon*,strider*} | \ - ./tools/moveconfig.py -Cy CONFIG_CMD_FPGAD -d - - - -Finding boards with particular CONFIG combinations --------------------------------------------------- - -You can use `moveconfig.py` to figure out which boards have a CONFIG enabled, or -which do not. To use it, first build a database:: - - ./tools/moveconfig.py -b - -Then you can run queries using the `-f` flag followed by a list of CONFIG terms. -Each term is CONFIG name, with or without a tilde (~) prefix. The tool searches -for boards which match the CONFIG name, or do not match if tilde is used. For -example, to find boards which enabled CONFIG_SCSI but not CONFIG_BLK:: - - tools/moveconfig.py -f SCSI ~BLK - 3 matches - pg_wcom_seli8_defconfig highbank_defconfig pg_wcom_expu1_defconfig - - -Finding implied CONFIGs ------------------------ - -Some CONFIG options can be implied by others and this can help to reduce -the size of the defconfig files. For example, CONFIG_X86 implies -CONFIG_CMD_IRQ, so we can put 'imply CMD_IRQ' under 'config X86' and -all x86 boards will have that option, avoiding adding CONFIG_CMD_IRQ to -each of the x86 defconfig files. - -This tool can help find such configs. To use it, first build a database:: - - ./tools/moveconfig.py -b - -Then try to query it:: - - ./tools/moveconfig.py -i CONFIG_I8042_KEYB - CONFIG_I8042_KEYB found in 33/5155 defconfigs - 28 : CONFIG_X86 - 28 : CONFIG_SA_PCIEX_LENGTH - 28 : CONFIG_HPET_ADDRESS - 28 : CONFIG_MAX_PIRQ_LINKS - 28 : CONFIG_I8254_TIMER - 28 : CONFIG_I8259_PIC - 28 : CONFIG_RAMBASE - 28 : CONFIG_IRQ_SLOT_COUNT - 28 : CONFIG_PCIE_ECAM_SIZE - 28 : CONFIG_APIC - ... - -This shows a list of config options which might imply CONFIG_I8042_KEYB along -with how many defconfigs they cover. From this you can see that CONFIG_X86 -generally implies CONFIG_I8042_KEYB but not always (28 out of 35). Therefore, -instead of adding CONFIG_I8042_KEYB to -the defconfig of every x86 board, you could add a single imply line to the -Kconfig file:: - - config X86 - bool "x86 architecture" - ... - imply CMD_EEPROM - -That will cover 28 defconfigs and you can perhaps find another condition that -indicates that CONFIG_I8042_KEYB is not needed for the remaining 5 boards. Many -of the options listed are not suitable as they are not related. E.g. it would be -odd for CONFIG_RAMBASE to imply CONFIG_I8042_KEYB. - -Using this search you can reduce the size of moveconfig patches. - -You can automatically add 'imply' statements in the Kconfig with the -a -option:: - - ./tools/moveconfig.py -s -i CONFIG_SCSI \ - -a CONFIG_ARCH_LS1021A,CONFIG_ARCH_LS1043A - -This will add 'imply SCSI' to the two CONFIG options mentioned, assuming that -the database indicates that they do actually imply CONFIG_SCSI and do not -already have an 'imply SCSI'. - -The output shows where the imply is added:: - - 18 : CONFIG_ARCH_LS1021A arch/arm/cpu/armv7/ls102xa/Kconfig:1 - 13 : CONFIG_ARCH_LS1043A arch/arm/cpu/armv8/fsl-layerscape/Kconfig:11 - 12 : CONFIG_ARCH_LS1046A arch/arm/cpu/armv8/fsl-layerscape/Kconfig:31 - -The first number is the number of boards which can avoid having a special -CONFIG_SCSI option in their defconfig file if this 'imply' is added. -The location at the right is the Kconfig file and line number where the config -appears. For example, adding 'imply CONFIG_SCSI' to the 'config ARCH_LS1021A' -in arch/arm/cpu/armv7/ls102xa/Kconfig at line 1 will help 18 boards to reduce -the size of their defconfig files. - -If you want to add an 'imply' to every imply config in the list, you can use:: - - ./tools/moveconfig.py -s -i CONFIG_SCSI -a all - -To control which ones are displayed, use -I where list is a list of -options (use '-I help' to see possible options and their meaning). - -To skip showing you options that already have an 'imply' attached, use -A. - -When you have finished adding 'imply' options you can regenerate the -defconfig files for affected boards with something like:: - - git show --stat | ./tools/moveconfig.py -s -d - - -This will regenerate only those defconfigs changed in the current commit. -If you start with (say) 100 defconfigs being changed in the commit, and add -a few 'imply' options as above, then regenerate, hopefully you can reduce the -number of defconfigs changed in the commit. - - -Available options ------------------ - - -c, --color - Surround each portion of the log with escape sequences to display it - in color on the terminal. - - -C, --commit - Create a git commit with the changes when the operation is complete. A - standard commit message is used which may need to be edited. - - -d, --defconfigs - Specify a file containing a list of defconfigs to move. The defconfig - files can be given with shell-style wildcards. Use '-' to read from stdin. - - -f, --find - Find boards with a given config combination - - -n, --dry-run - Perform a trial run that does not make any changes. It is useful to - see what is going to happen before one actually runs it. - - -e, --exit-on-error - Exit immediately if Make exits with a non-zero status while processing - a defconfig file. - - -s, --force-sync - Do "make savedefconfig" forcibly for all the defconfig files. - If not specified, "make savedefconfig" only occurs for cases - where at least one CONFIG was moved. - - -S, --spl - Look for moved config options in spl/include/autoconf.mk instead of - include/autoconf.mk. This is useful for moving options for SPL build - because SPL related options (mostly prefixed with CONFIG_SPL\_) are - sometimes blocked by CONFIG_SPL_BUILD ifdef conditionals. - - -H, --headers-only - Only cleanup the headers; skip the defconfig processing - - -j, --jobs - Specify the number of threads to run simultaneously. If not specified, - the number of threads is the same as the number of CPU cores. - - -r, --git-ref - Specify the git ref to clone for building the autoconf.mk. If unspecified - use the CWD. This is useful for when changes to the Kconfig affect the - default values and you want to capture the state of the defconfig from - before that change was in effect. If in doubt, specify a ref pre-Kconfig - changes (use HEAD if Kconfig changes are not committed). Worst case it will - take a bit longer to run, but will always do the right thing. - - -v, --verbose - Show any build errors as boards are built - - -y, --yes - Instead of prompting, automatically go ahead with all operations. This - includes cleaning up headers, the config whitelist and the README. - -To see the complete list of supported options, run:: - - tools/moveconfig.py -h diff --git a/doc/develop/qconfig.rst b/doc/develop/qconfig.rst new file mode 100644 index 0000000..8efb1eb --- /dev/null +++ b/doc/develop/qconfig.rst @@ -0,0 +1,234 @@ +.. SPDX-License-Identifier: GPL-2.0+ + +qconfig - Querying CONFIG options +================================= + +It is not possible to see all the CONFIG options used by a board without +building its `.config` file. This tool allows this to be done efficiently for +all boards, or a subset, writing the results to a unified database file. + +This database can be queried, to find boards which used a certain combination +of options, to aid in discovering Kconfig options which imply others. + +The tool also permits syncing of defconfigs, which corrects the ordering and +drops options which are implied by others. + +Finally, it allows scanning the source code to look for inconsistencies in the +use of Kconfig options. + +Installation +------------ + +You may need to install 'python3-asteval' for the 'asteval' module. + +How does it work? +----------------- + +When building a database (`-b`), this tool runs configuration and builds +include/autoconf.mk for every defconfig. The config options defined in Kconfig +appear in the .config file (unless they are hidden because of unmet dependency.) +On the other hand, the config options defined by board headers are seen +in include/autoconf.mk. + +When resyncing defconfigs (`-s`) the .config is synced by "make savedefconfig" +and the defconfig is updated with it. + +For faster processing, this tool is multi-threaded. It creates +separate build directories where the out-of-tree build is run. The +temporary build directories are automatically created and deleted as +needed. The number of threads are chosen based on the number of the CPU +cores of your system although you can change it via -j (--jobs) option. + +Note that `*.config` fragments are not supported. + +Toolchains +---------- + +Appropriate toolchains are necessary to generate include/autoconf.mk +for all the architectures supported by U-Boot. Most of them are available +at the kernel.org site. This tool uses the same tools as +:doc:`../build/buildman`, so you can use `buildman --fetch-arch` to fetch +toolchains. + + +Examples +-------- + +To sync only X86 defconfigs:: + + ./tools/qconfig.py -s -d <(grep -l X86 configs/*) + +or:: + + grep -l X86 configs/* | ./tools/qconfig.py -s -d - + +To process CONFIG_CMD_FPGAD only for a subset of configs based on path match:: + + ls configs/{hrcon*,iocon*,strider*} | \ + ./tools/qconfig.py -C CONFIG_CMD_FPGAD -d - + + +Finding boards with particular CONFIG combinations +-------------------------------------------------- + +You can use `qconfig.py` to figure out which boards have a CONFIG enabled, or +which do not. To use it, first build a database:: + + ./tools/qconfig.py -b + +Then you can run queries using the `-f` flag followed by a list of CONFIG terms. +Each term is CONFIG name, with or without a tilde (~) prefix. The tool searches +for boards which match the CONFIG name, or do not match if tilde is used. For +example, to find boards which enabled CONFIG_SCSI but not CONFIG_BLK:: + + tools/qconfig.py -f SCSI ~BLK + 3 matches + pg_wcom_seli8_defconfig highbank_defconfig pg_wcom_expu1_defconfig + + +Finding implied CONFIGs +----------------------- + +Some CONFIG options can be implied by others and this can help to reduce +the size of the defconfig files. For example, CONFIG_X86 implies +CONFIG_CMD_IRQ, so we can put 'imply CMD_IRQ' under 'config X86' and +all x86 boards will have that option, avoiding adding CONFIG_CMD_IRQ to +each of the x86 defconfig files. + +This tool can help find such configs. To use it, first build a database:: + + ./tools/qconfig.py -b + +Then try to query it:: + + ./tools/qconfig.py -i CONFIG_I8042_KEYB + CONFIG_I8042_KEYB found in 33/5155 defconfigs + 28 : CONFIG_X86 + 28 : CONFIG_SA_PCIEX_LENGTH + 28 : CONFIG_HPET_ADDRESS + 28 : CONFIG_MAX_PIRQ_LINKS + 28 : CONFIG_I8254_TIMER + 28 : CONFIG_I8259_PIC + 28 : CONFIG_RAMBASE + 28 : CONFIG_IRQ_SLOT_COUNT + 28 : CONFIG_PCIE_ECAM_SIZE + 28 : CONFIG_APIC + ... + +This shows a list of config options which might imply CONFIG_I8042_KEYB along +with how many defconfigs they cover. From this you can see that CONFIG_X86 +generally implies CONFIG_I8042_KEYB but not always (28 out of 35). Therefore, +instead of adding CONFIG_I8042_KEYB to +the defconfig of every x86 board, you could add a single imply line to the +Kconfig file:: + + config X86 + bool "x86 architecture" + ... + imply CMD_EEPROM + +That will cover 28 defconfigs and you can perhaps find another condition that +indicates that CONFIG_I8042_KEYB is not needed for the remaining 5 boards. Many +of the options listed are not suitable as they are not related. E.g. it would be +odd for CONFIG_RAMBASE to imply CONFIG_I8042_KEYB. + +Using this search you can reduce the size of qconfig patches. + +You can automatically add 'imply' statements in the Kconfig with the -a +option:: + + ./tools/qconfig.py -s -i CONFIG_SCSI \ + -a CONFIG_ARCH_LS1021A,CONFIG_ARCH_LS1043A + +This will add 'imply SCSI' to the two CONFIG options mentioned, assuming that +the database indicates that they do actually imply CONFIG_SCSI and do not +already have an 'imply SCSI'. + +The output shows where the imply is added:: + + 18 : CONFIG_ARCH_LS1021A arch/arm/cpu/armv7/ls102xa/Kconfig:1 + 13 : CONFIG_ARCH_LS1043A arch/arm/cpu/armv8/fsl-layerscape/Kconfig:11 + 12 : CONFIG_ARCH_LS1046A arch/arm/cpu/armv8/fsl-layerscape/Kconfig:31 + +The first number is the number of boards which can avoid having a special +CONFIG_SCSI option in their defconfig file if this 'imply' is added. +The location at the right is the Kconfig file and line number where the config +appears. For example, adding 'imply CONFIG_SCSI' to the 'config ARCH_LS1021A' +in arch/arm/cpu/armv7/ls102xa/Kconfig at line 1 will help 18 boards to reduce +the size of their defconfig files. + +If you want to add an 'imply' to every imply config in the list, you can use:: + + ./tools/qconfig.py -s -i CONFIG_SCSI -a all + +To control which ones are displayed, use -I where list is a list of +options (use '-I help' to see possible options and their meaning). + +To skip showing you options that already have an 'imply' attached, use -A. + +When you have finished adding 'imply' options you can regenerate the +defconfig files for affected boards with something like:: + + git show --stat | ./tools/qconfig.py -s -d - + +This will regenerate only those defconfigs changed in the current commit. +If you start with (say) 100 defconfigs being changed in the commit, and add +a few 'imply' options as above, then regenerate, hopefully you can reduce the +number of defconfigs changed in the commit. + + +Available options +----------------- + + --nocolour + Disables colouring of output. This is normally used when writing to a + terminal. + + -C, --commit + Create a git commit with the changes when the operation is complete. A + standard commit message is used which may need to be edited. + + -d, --defconfigs + Specify a file containing a list of defconfigs to move. The defconfig + files can be given with shell-style wildcards. Use '-' to read from stdin. + + -f, --find + Find boards with a given config combination + + -n, --dry-run + Perform a trial run that does not make any changes. It is useful to + see what is going to happen before one actually runs it. + + -e, --exit-on-error + Exit immediately if Make exits with a non-zero status while processing + a defconfig file. + + -s, --force-sync + Do "make savedefconfig" forcibly for all the defconfig files. + If not specified, "make savedefconfig" only occurs for cases + where at least one CONFIG was moved. + + -S, --spl + Look for moved config options in spl/include/autoconf.mk instead of + include/autoconf.mk. This is useful for moving options for SPL build + because SPL related options (mostly prefixed with CONFIG_SPL\_) are + sometimes blocked by CONFIG_SPL_BUILD ifdef conditionals. + + -j, --jobs + Specify the number of threads to run simultaneously. If not specified, + the number of threads is the same as the number of CPU cores. + + -r, --git-ref + Specify the git ref to clone for building the autoconf.mk. If unspecified + use the CWD. This is useful for when changes to the Kconfig affect the + default values and you want to capture the state of the defconfig from + before that change was in effect. If in doubt, specify a ref pre-Kconfig + changes (use HEAD if Kconfig changes are not committed). Worst case it will + take a bit longer to run, but will always do the right thing. + + -v, --verbose + Show any build errors as boards are built + +To see the complete list of supported options, run:: + + tools/qconfig.py -h -- cgit v1.1