blob: 36361f9ed1b6c70b05bed13443c750e1d2806e12 [file] [log] [blame]
Simon Glass793dca32019-10-31 07:42:57 -06001#!/usr/bin/env python3
Tom Rini83d290c2018-05-06 17:58:06 -04002# SPDX-License-Identifier: GPL-2.0+
Masahiro Yamada5a27c732015-05-20 11:36:07 +09003#
4# Author: Masahiro Yamada <yamada.masahiro@socionext.com>
5#
Masahiro Yamada5a27c732015-05-20 11:36:07 +09006
7"""
8Move config options from headers to defconfig files.
9
10Since Kconfig was introduced to U-Boot, we have worked on moving
11config options from headers to Kconfig (defconfig).
12
13This tool intends to help this tremendous work.
14
15
16Usage
17-----
18
Masahiro Yamadab6ef3932016-05-19 15:51:58 +090019First, you must edit the Kconfig to add the menu entries for the configs
Joe Hershberger96464ba2015-05-19 13:21:17 -050020you are moving.
21
Masahiro Yamadab6ef3932016-05-19 15:51:58 +090022And then run this tool giving CONFIG names you want to move.
23For example, if you want to move CONFIG_CMD_USB and CONFIG_SYS_TEXT_BASE,
24simply type as follows:
Masahiro Yamada5a27c732015-05-20 11:36:07 +090025
Masahiro Yamadab6ef3932016-05-19 15:51:58 +090026 $ tools/moveconfig.py CONFIG_CMD_USB CONFIG_SYS_TEXT_BASE
Masahiro Yamada5a27c732015-05-20 11:36:07 +090027
Masahiro Yamadab6ef3932016-05-19 15:51:58 +090028The tool walks through all the defconfig files and move the given CONFIGs.
Masahiro Yamada5a27c732015-05-20 11:36:07 +090029
30The log is also displayed on the terminal.
31
Masahiro Yamada1d085562016-05-19 15:52:02 +090032The log is printed for each defconfig as follows:
Masahiro Yamada5a27c732015-05-20 11:36:07 +090033
Masahiro Yamada1d085562016-05-19 15:52:02 +090034<defconfig_name>
35 <action1>
36 <action2>
37 <action3>
38 ...
Masahiro Yamada5a27c732015-05-20 11:36:07 +090039
Masahiro Yamada1d085562016-05-19 15:52:02 +090040<defconfig_name> is the name of the defconfig.
41
42<action*> shows what the tool did for that defconfig.
Masahiro Yamadac21fc7e2016-08-21 16:12:36 +090043It looks like one of the following:
Masahiro Yamada5a27c732015-05-20 11:36:07 +090044
45 - Move 'CONFIG_... '
46 This config option was moved to the defconfig
47
Masahiro Yamadacc008292016-05-19 15:51:56 +090048 - CONFIG_... is not defined in Kconfig. Do nothing.
Masahiro Yamada916224c2016-08-22 22:18:21 +090049 The entry for this CONFIG was not found in Kconfig. The option is not
50 defined in the config header, either. So, this case can be just skipped.
51
52 - CONFIG_... is not defined in Kconfig (suspicious). Do nothing.
53 This option is defined in the config header, but its entry was not found
54 in Kconfig.
Masahiro Yamadacc008292016-05-19 15:51:56 +090055 There are two common cases:
56 - You forgot to create an entry for the CONFIG before running
57 this tool, or made a typo in a CONFIG passed to this tool.
58 - The entry was hidden due to unmet 'depends on'.
Masahiro Yamada916224c2016-08-22 22:18:21 +090059 The tool does not know if the result is reasonable, so please check it
60 manually.
Masahiro Yamada5a27c732015-05-20 11:36:07 +090061
Masahiro Yamadacc008292016-05-19 15:51:56 +090062 - 'CONFIG_...' is the same as the define in Kconfig. Do nothing.
63 The define in the config header matched the one in Kconfig.
64 We do not need to touch it.
Masahiro Yamada5a27c732015-05-20 11:36:07 +090065
Masahiro Yamada90ed6cb2016-05-19 15:51:53 +090066 - Compiler is missing. Do nothing.
67 The compiler specified for this architecture was not found
68 in your PATH environment.
69 (If -e option is passed, the tool exits immediately.)
70
71 - Failed to process.
Masahiro Yamada5a27c732015-05-20 11:36:07 +090072 An error occurred during processing this defconfig. Skipped.
73 (If -e option is passed, the tool exits immediately on error.)
74
75Finally, you will be asked, Clean up headers? [y/n]:
76
77If you say 'y' here, the unnecessary config defines are removed
78from the config headers (include/configs/*.h).
79It just uses the regex method, so you should not rely on it.
80Just in case, please do 'git diff' to see what happened.
81
82
Masahiro Yamadab6ef3932016-05-19 15:51:58 +090083How does it work?
84-----------------
Masahiro Yamada5a27c732015-05-20 11:36:07 +090085
86This tool runs configuration and builds include/autoconf.mk for every
87defconfig. The config options defined in Kconfig appear in the .config
88file (unless they are hidden because of unmet dependency.)
89On the other hand, the config options defined by board headers are seen
90in include/autoconf.mk. The tool looks for the specified options in both
Masahiro Yamadab6ef3932016-05-19 15:51:58 +090091of them to decide the appropriate action for the options. If the given
92config option is found in the .config, but its value does not match the
93one from the board header, the config option in the .config is replaced
94with the define in the board header. Then, the .config is synced by
95"make savedefconfig" and the defconfig is updated with it.
Masahiro Yamada5a27c732015-05-20 11:36:07 +090096
97For faster processing, this tool handles multi-threading. It creates
98separate build directories where the out-of-tree build is run. The
99temporary build directories are automatically created and deleted as
100needed. The number of threads are chosen based on the number of the CPU
101cores of your system although you can change it via -j (--jobs) option.
102
103
104Toolchains
105----------
106
107Appropriate toolchain are necessary to generate include/autoconf.mk
108for all the architectures supported by U-Boot. Most of them are available
Simon Glass6821a742017-07-10 14:47:47 -0600109at the kernel.org site, some are not provided by kernel.org. This tool uses
110the same tools as buildman, so see that tool for setup (e.g. --fetch-arch).
Masahiro Yamada5a27c732015-05-20 11:36:07 +0900111
112
Simon Glassddf91c62017-06-01 19:39:00 -0600113Tips and trips
114--------------
115
116To sync only X86 defconfigs:
117
118 ./tools/moveconfig.py -s -d <(grep -l X86 configs/*)
119
120or:
121
122 grep -l X86 configs/* | ./tools/moveconfig.py -s -d -
123
124To process CONFIG_CMD_FPGAD only for a subset of configs based on path match:
125
126 ls configs/{hrcon*,iocon*,strider*} | \
127 ./tools/moveconfig.py -Cy CONFIG_CMD_FPGAD -d -
128
129
Simon Glass99b66602017-06-01 19:39:03 -0600130Finding implied CONFIGs
131-----------------------
132
133Some CONFIG options can be implied by others and this can help to reduce
134the size of the defconfig files. For example, CONFIG_X86 implies
135CONFIG_CMD_IRQ, so we can put 'imply CMD_IRQ' under 'config X86' and
136all x86 boards will have that option, avoiding adding CONFIG_CMD_IRQ to
137each of the x86 defconfig files.
138
139This tool can help find such configs. To use it, first build a database:
140
141 ./tools/moveconfig.py -b
142
143Then try to query it:
144
145 ./tools/moveconfig.py -i CONFIG_CMD_IRQ
146 CONFIG_CMD_IRQ found in 311/2384 defconfigs
147 44 : CONFIG_SYS_FSL_ERRATUM_IFC_A002769
148 41 : CONFIG_SYS_FSL_ERRATUM_A007075
149 31 : CONFIG_SYS_FSL_DDR_VER_44
150 28 : CONFIG_ARCH_P1010
151 28 : CONFIG_SYS_FSL_ERRATUM_P1010_A003549
152 28 : CONFIG_SYS_FSL_ERRATUM_SEC_A003571
153 28 : CONFIG_SYS_FSL_ERRATUM_IFC_A003399
154 25 : CONFIG_SYS_FSL_ERRATUM_A008044
155 22 : CONFIG_ARCH_P1020
156 21 : CONFIG_SYS_FSL_DDR_VER_46
157 20 : CONFIG_MAX_PIRQ_LINKS
158 20 : CONFIG_HPET_ADDRESS
159 20 : CONFIG_X86
160 20 : CONFIG_PCIE_ECAM_SIZE
161 20 : CONFIG_IRQ_SLOT_COUNT
162 20 : CONFIG_I8259_PIC
163 20 : CONFIG_CPU_ADDR_BITS
164 20 : CONFIG_RAMBASE
165 20 : CONFIG_SYS_FSL_ERRATUM_A005871
166 20 : CONFIG_PCIE_ECAM_BASE
167 20 : CONFIG_X86_TSC_TIMER
168 20 : CONFIG_I8254_TIMER
169 20 : CONFIG_CMD_GETTIME
170 19 : CONFIG_SYS_FSL_ERRATUM_A005812
171 18 : CONFIG_X86_RUN_32BIT
172 17 : CONFIG_CMD_CHIP_CONFIG
173 ...
174
175This shows a list of config options which might imply CONFIG_CMD_EEPROM along
176with how many defconfigs they cover. From this you can see that CONFIG_X86
177implies CONFIG_CMD_EEPROM. Therefore, instead of adding CONFIG_CMD_EEPROM to
178the defconfig of every x86 board, you could add a single imply line to the
179Kconfig file:
180
181 config X86
182 bool "x86 architecture"
183 ...
184 imply CMD_EEPROM
185
186That will cover 20 defconfigs. Many of the options listed are not suitable as
187they are not related. E.g. it would be odd for CONFIG_CMD_GETTIME to imply
188CMD_EEPROM.
189
190Using this search you can reduce the size of moveconfig patches.
191
Simon Glasscb008832017-06-15 21:39:33 -0600192You can automatically add 'imply' statements in the Kconfig with the -a
193option:
194
195 ./tools/moveconfig.py -s -i CONFIG_SCSI \
196 -a CONFIG_ARCH_LS1021A,CONFIG_ARCH_LS1043A
197
198This will add 'imply SCSI' to the two CONFIG options mentioned, assuming that
199the database indicates that they do actually imply CONFIG_SCSI and do not
200already have an 'imply SCSI'.
201
202The output shows where the imply is added:
203
204 18 : CONFIG_ARCH_LS1021A arch/arm/cpu/armv7/ls102xa/Kconfig:1
205 13 : CONFIG_ARCH_LS1043A arch/arm/cpu/armv8/fsl-layerscape/Kconfig:11
206 12 : CONFIG_ARCH_LS1046A arch/arm/cpu/armv8/fsl-layerscape/Kconfig:31
207
208The first number is the number of boards which can avoid having a special
209CONFIG_SCSI option in their defconfig file if this 'imply' is added.
210The location at the right is the Kconfig file and line number where the config
211appears. For example, adding 'imply CONFIG_SCSI' to the 'config ARCH_LS1021A'
212in arch/arm/cpu/armv7/ls102xa/Kconfig at line 1 will help 18 boards to reduce
213the size of their defconfig files.
214
215If you want to add an 'imply' to every imply config in the list, you can use
216
217 ./tools/moveconfig.py -s -i CONFIG_SCSI -a all
218
219To control which ones are displayed, use -I <list> where list is a list of
220options (use '-I help' to see possible options and their meaning).
221
222To skip showing you options that already have an 'imply' attached, use -A.
223
224When you have finished adding 'imply' options you can regenerate the
225defconfig files for affected boards with something like:
226
227 git show --stat | ./tools/moveconfig.py -s -d -
228
229This will regenerate only those defconfigs changed in the current commit.
230If you start with (say) 100 defconfigs being changed in the commit, and add
231a few 'imply' options as above, then regenerate, hopefully you can reduce the
232number of defconfigs changed in the commit.
233
Simon Glass99b66602017-06-01 19:39:03 -0600234
Masahiro Yamada5a27c732015-05-20 11:36:07 +0900235Available options
236-----------------
237
238 -c, --color
239 Surround each portion of the log with escape sequences to display it
240 in color on the terminal.
241
Simon Glass9ede2122016-09-12 23:18:21 -0600242 -C, --commit
243 Create a git commit with the changes when the operation is complete. A
244 standard commit message is used which may need to be edited.
245
Joe Hershberger91040e82015-05-19 13:21:19 -0500246 -d, --defconfigs
Masahiro Yamada0dbc9b52016-10-19 14:39:54 +0900247 Specify a file containing a list of defconfigs to move. The defconfig
Simon Glassddf91c62017-06-01 19:39:00 -0600248 files can be given with shell-style wildcards. Use '-' to read from stdin.
Joe Hershberger91040e82015-05-19 13:21:19 -0500249
Masahiro Yamada5a27c732015-05-20 11:36:07 +0900250 -n, --dry-run
Masahiro Yamadab6ef3932016-05-19 15:51:58 +0900251 Perform a trial run that does not make any changes. It is useful to
Masahiro Yamada5a27c732015-05-20 11:36:07 +0900252 see what is going to happen before one actually runs it.
253
254 -e, --exit-on-error
255 Exit immediately if Make exits with a non-zero status while processing
256 a defconfig file.
257
Masahiro Yamada8513dc02016-05-19 15:52:08 +0900258 -s, --force-sync
259 Do "make savedefconfig" forcibly for all the defconfig files.
260 If not specified, "make savedefconfig" only occurs for cases
261 where at least one CONFIG was moved.
262
Masahiro Yamada07913d12016-08-22 22:18:22 +0900263 -S, --spl
264 Look for moved config options in spl/include/autoconf.mk instead of
265 include/autoconf.mk. This is useful for moving options for SPL build
266 because SPL related options (mostly prefixed with CONFIG_SPL_) are
267 sometimes blocked by CONFIG_SPL_BUILD ifdef conditionals.
268
Joe Hershberger2144f882015-05-19 13:21:20 -0500269 -H, --headers-only
270 Only cleanup the headers; skip the defconfig processing
271
Masahiro Yamada5a27c732015-05-20 11:36:07 +0900272 -j, --jobs
273 Specify the number of threads to run simultaneously. If not specified,
274 the number of threads is the same as the number of CPU cores.
275
Joe Hershberger6b96c1a2016-06-10 14:53:32 -0500276 -r, --git-ref
277 Specify the git ref to clone for building the autoconf.mk. If unspecified
278 use the CWD. This is useful for when changes to the Kconfig affect the
279 default values and you want to capture the state of the defconfig from
280 before that change was in effect. If in doubt, specify a ref pre-Kconfig
281 changes (use HEAD if Kconfig changes are not committed). Worst case it will
282 take a bit longer to run, but will always do the right thing.
283
Joe Hershberger95bf9c72015-05-19 13:21:24 -0500284 -v, --verbose
285 Show any build errors as boards are built
286
Simon Glass6b403df2016-09-12 23:18:20 -0600287 -y, --yes
288 Instead of prompting, automatically go ahead with all operations. This
Simon Glassddf91c62017-06-01 19:39:00 -0600289 includes cleaning up headers, CONFIG_SYS_EXTRA_OPTIONS, the config whitelist
290 and the README.
Simon Glass6b403df2016-09-12 23:18:20 -0600291
Masahiro Yamada5a27c732015-05-20 11:36:07 +0900292To see the complete list of supported options, run
293
294 $ tools/moveconfig.py -h
295
296"""
297
Markus Klotzbuecherb3192f42020-02-12 20:46:44 +0100298import asteval
Simon Glass99b66602017-06-01 19:39:03 -0600299import collections
Masahiro Yamada8ba1f5d2016-07-25 19:15:24 +0900300import copy
Masahiro Yamadaf2f69812016-07-25 19:15:25 +0900301import difflib
Masahiro Yamadac8e1b102016-05-19 15:52:07 +0900302import filecmp
Masahiro Yamada5a27c732015-05-20 11:36:07 +0900303import fnmatch
Masahiro Yamada0dbc9b52016-10-19 14:39:54 +0900304import glob
Masahiro Yamada5a27c732015-05-20 11:36:07 +0900305import multiprocessing
306import optparse
307import os
Simon Glass793dca32019-10-31 07:42:57 -0600308import queue
Masahiro Yamada5a27c732015-05-20 11:36:07 +0900309import re
310import shutil
311import subprocess
312import sys
313import tempfile
Simon Glassd73fcb12017-06-01 19:39:02 -0600314import threading
Masahiro Yamada5a27c732015-05-20 11:36:07 +0900315import time
316
Simon Glass0ede00f2020-04-17 18:09:02 -0600317from buildman import bsettings
318from buildman import kconfiglib
319from buildman import toolchain
Simon Glasscb008832017-06-15 21:39:33 -0600320
Masahiro Yamada5a27c732015-05-20 11:36:07 +0900321SHOW_GNU_MAKE = 'scripts/show-gnu-make'
322SLEEP_TIME=0.03
323
Masahiro Yamada5a27c732015-05-20 11:36:07 +0900324STATE_IDLE = 0
325STATE_DEFCONFIG = 1
326STATE_AUTOCONF = 2
Joe Hershberger96464ba2015-05-19 13:21:17 -0500327STATE_SAVEDEFCONFIG = 3
Masahiro Yamada5a27c732015-05-20 11:36:07 +0900328
329ACTION_MOVE = 0
Masahiro Yamadacc008292016-05-19 15:51:56 +0900330ACTION_NO_ENTRY = 1
Masahiro Yamada916224c2016-08-22 22:18:21 +0900331ACTION_NO_ENTRY_WARN = 2
332ACTION_NO_CHANGE = 3
Masahiro Yamada5a27c732015-05-20 11:36:07 +0900333
334COLOR_BLACK = '0;30'
335COLOR_RED = '0;31'
336COLOR_GREEN = '0;32'
337COLOR_BROWN = '0;33'
338COLOR_BLUE = '0;34'
339COLOR_PURPLE = '0;35'
340COLOR_CYAN = '0;36'
341COLOR_LIGHT_GRAY = '0;37'
342COLOR_DARK_GRAY = '1;30'
343COLOR_LIGHT_RED = '1;31'
344COLOR_LIGHT_GREEN = '1;32'
345COLOR_YELLOW = '1;33'
346COLOR_LIGHT_BLUE = '1;34'
347COLOR_LIGHT_PURPLE = '1;35'
348COLOR_LIGHT_CYAN = '1;36'
349COLOR_WHITE = '1;37'
350
Simon Glassf3b8e642017-06-01 19:39:01 -0600351AUTO_CONF_PATH = 'include/config/auto.conf'
Simon Glassd73fcb12017-06-01 19:39:02 -0600352CONFIG_DATABASE = 'moveconfig.db'
Simon Glassf3b8e642017-06-01 19:39:01 -0600353
Simon Glasscb008832017-06-15 21:39:33 -0600354CONFIG_LEN = len('CONFIG_')
Simon Glassf3b8e642017-06-01 19:39:01 -0600355
Markus Klotzbuecherb237d352019-05-15 15:15:52 +0200356SIZES = {
357 "SZ_1": 0x00000001, "SZ_2": 0x00000002,
358 "SZ_4": 0x00000004, "SZ_8": 0x00000008,
359 "SZ_16": 0x00000010, "SZ_32": 0x00000020,
360 "SZ_64": 0x00000040, "SZ_128": 0x00000080,
361 "SZ_256": 0x00000100, "SZ_512": 0x00000200,
362 "SZ_1K": 0x00000400, "SZ_2K": 0x00000800,
363 "SZ_4K": 0x00001000, "SZ_8K": 0x00002000,
364 "SZ_16K": 0x00004000, "SZ_32K": 0x00008000,
365 "SZ_64K": 0x00010000, "SZ_128K": 0x00020000,
366 "SZ_256K": 0x00040000, "SZ_512K": 0x00080000,
367 "SZ_1M": 0x00100000, "SZ_2M": 0x00200000,
368 "SZ_4M": 0x00400000, "SZ_8M": 0x00800000,
369 "SZ_16M": 0x01000000, "SZ_32M": 0x02000000,
370 "SZ_64M": 0x04000000, "SZ_128M": 0x08000000,
371 "SZ_256M": 0x10000000, "SZ_512M": 0x20000000,
372 "SZ_1G": 0x40000000, "SZ_2G": 0x80000000,
373 "SZ_4G": 0x100000000
374}
375
Masahiro Yamada5a27c732015-05-20 11:36:07 +0900376### helper functions ###
377def get_devnull():
378 """Get the file object of '/dev/null' device."""
379 try:
380 devnull = subprocess.DEVNULL # py3k
381 except AttributeError:
382 devnull = open(os.devnull, 'wb')
383 return devnull
384
385def check_top_directory():
386 """Exit if we are not at the top of source directory."""
387 for f in ('README', 'Licenses'):
388 if not os.path.exists(f):
389 sys.exit('Please run at the top of source directory.')
390
Masahiro Yamadabd63e5b2016-05-19 15:51:54 +0900391def check_clean_directory():
392 """Exit if the source tree is not clean."""
393 for f in ('.config', 'include/config'):
394 if os.path.exists(f):
395 sys.exit("source tree is not clean, please run 'make mrproper'")
396
Masahiro Yamada5a27c732015-05-20 11:36:07 +0900397def get_make_cmd():
398 """Get the command name of GNU Make.
399
400 U-Boot needs GNU Make for building, but the command name is not
401 necessarily "make". (for example, "gmake" on FreeBSD).
402 Returns the most appropriate command name on your system.
403 """
404 process = subprocess.Popen([SHOW_GNU_MAKE], stdout=subprocess.PIPE)
405 ret = process.communicate()
406 if process.returncode:
407 sys.exit('GNU Make not found')
408 return ret[0].rstrip()
409
Simon Glass25f978c2017-06-01 19:38:58 -0600410def get_matched_defconfig(line):
411 """Get the defconfig files that match a pattern
412
413 Args:
414 line: Path or filename to match, e.g. 'configs/snow_defconfig' or
415 'k2*_defconfig'. If no directory is provided, 'configs/' is
416 prepended
417
418 Returns:
419 a list of matching defconfig files
420 """
421 dirname = os.path.dirname(line)
422 if dirname:
423 pattern = line
424 else:
425 pattern = os.path.join('configs', line)
426 return glob.glob(pattern) + glob.glob(pattern + '_defconfig')
427
Masahiro Yamada0dbc9b52016-10-19 14:39:54 +0900428def get_matched_defconfigs(defconfigs_file):
Simon Glassee4e61b2017-06-01 19:38:59 -0600429 """Get all the defconfig files that match the patterns in a file.
430
431 Args:
432 defconfigs_file: File containing a list of defconfigs to process, or
433 '-' to read the list from stdin
434
435 Returns:
436 A list of paths to defconfig files, with no duplicates
437 """
Masahiro Yamada0dbc9b52016-10-19 14:39:54 +0900438 defconfigs = []
Simon Glassee4e61b2017-06-01 19:38:59 -0600439 if defconfigs_file == '-':
440 fd = sys.stdin
441 defconfigs_file = 'stdin'
442 else:
443 fd = open(defconfigs_file)
444 for i, line in enumerate(fd):
Masahiro Yamada0dbc9b52016-10-19 14:39:54 +0900445 line = line.strip()
446 if not line:
447 continue # skip blank lines silently
Simon Glass2ddd85d2017-06-15 21:39:31 -0600448 if ' ' in line:
449 line = line.split(' ')[0] # handle 'git log' input
Simon Glass25f978c2017-06-01 19:38:58 -0600450 matched = get_matched_defconfig(line)
Masahiro Yamada0dbc9b52016-10-19 14:39:54 +0900451 if not matched:
Simon Glass793dca32019-10-31 07:42:57 -0600452 print("warning: %s:%d: no defconfig matched '%s'" % \
453 (defconfigs_file, i + 1, line), file=sys.stderr)
Masahiro Yamada0dbc9b52016-10-19 14:39:54 +0900454
455 defconfigs += matched
456
457 # use set() to drop multiple matching
458 return [ defconfig[len('configs') + 1:] for defconfig in set(defconfigs) ]
459
Masahiro Yamada684c3062016-07-25 19:15:28 +0900460def get_all_defconfigs():
461 """Get all the defconfig files under the configs/ directory."""
462 defconfigs = []
463 for (dirpath, dirnames, filenames) in os.walk('configs'):
464 dirpath = dirpath[len('configs') + 1:]
465 for filename in fnmatch.filter(filenames, '*_defconfig'):
466 defconfigs.append(os.path.join(dirpath, filename))
467
468 return defconfigs
469
Masahiro Yamada5a27c732015-05-20 11:36:07 +0900470def color_text(color_enabled, color, string):
471 """Return colored string."""
472 if color_enabled:
Masahiro Yamada1d085562016-05-19 15:52:02 +0900473 # LF should not be surrounded by the escape sequence.
474 # Otherwise, additional whitespace or line-feed might be printed.
475 return '\n'.join([ '\033[' + color + 'm' + s + '\033[0m' if s else ''
476 for s in string.split('\n') ])
Masahiro Yamada5a27c732015-05-20 11:36:07 +0900477 else:
478 return string
479
Masahiro Yamadae9ea1222016-07-25 19:15:26 +0900480def show_diff(a, b, file_path, color_enabled):
Masahiro Yamadaf2f69812016-07-25 19:15:25 +0900481 """Show unidified diff.
482
483 Arguments:
484 a: A list of lines (before)
485 b: A list of lines (after)
486 file_path: Path to the file
Masahiro Yamadae9ea1222016-07-25 19:15:26 +0900487 color_enabled: Display the diff in color
Masahiro Yamadaf2f69812016-07-25 19:15:25 +0900488 """
489
490 diff = difflib.unified_diff(a, b,
491 fromfile=os.path.join('a', file_path),
492 tofile=os.path.join('b', file_path))
493
494 for line in diff:
Masahiro Yamadae9ea1222016-07-25 19:15:26 +0900495 if line[0] == '-' and line[1] != '-':
Simon Glass793dca32019-10-31 07:42:57 -0600496 print(color_text(color_enabled, COLOR_RED, line), end=' ')
Masahiro Yamadae9ea1222016-07-25 19:15:26 +0900497 elif line[0] == '+' and line[1] != '+':
Simon Glass793dca32019-10-31 07:42:57 -0600498 print(color_text(color_enabled, COLOR_GREEN, line), end=' ')
Masahiro Yamadae9ea1222016-07-25 19:15:26 +0900499 else:
Simon Glass793dca32019-10-31 07:42:57 -0600500 print(line, end=' ')
Masahiro Yamadaf2f69812016-07-25 19:15:25 +0900501
Masahiro Yamada8ba1f5d2016-07-25 19:15:24 +0900502def extend_matched_lines(lines, matched, pre_patterns, post_patterns, extend_pre,
503 extend_post):
504 """Extend matched lines if desired patterns are found before/after already
505 matched lines.
506
507 Arguments:
508 lines: A list of lines handled.
509 matched: A list of line numbers that have been already matched.
510 (will be updated by this function)
511 pre_patterns: A list of regular expression that should be matched as
512 preamble.
513 post_patterns: A list of regular expression that should be matched as
514 postamble.
515 extend_pre: Add the line number of matched preamble to the matched list.
516 extend_post: Add the line number of matched postamble to the matched list.
517 """
518 extended_matched = []
519
520 j = matched[0]
521
522 for i in matched:
523 if i == 0 or i < j:
524 continue
525 j = i
526 while j in matched:
527 j += 1
528 if j >= len(lines):
529 break
530
531 for p in pre_patterns:
532 if p.search(lines[i - 1]):
533 break
534 else:
535 # not matched
536 continue
537
538 for p in post_patterns:
539 if p.search(lines[j]):
540 break
541 else:
542 # not matched
543 continue
544
545 if extend_pre:
546 extended_matched.append(i - 1)
547 if extend_post:
548 extended_matched.append(j)
549
550 matched += extended_matched
551 matched.sort()
552
Chris Packham85edfc12017-05-02 21:30:46 +1200553def confirm(options, prompt):
554 if not options.yes:
555 while True:
Simon Glass793dca32019-10-31 07:42:57 -0600556 choice = input('{} [y/n]: '.format(prompt))
Chris Packham85edfc12017-05-02 21:30:46 +1200557 choice = choice.lower()
Simon Glass793dca32019-10-31 07:42:57 -0600558 print(choice)
Chris Packham85edfc12017-05-02 21:30:46 +1200559 if choice == 'y' or choice == 'n':
560 break
561
562 if choice == 'n':
563 return False
564
565 return True
566
Chris Packham4d9dbb12019-01-30 20:23:16 +1300567def cleanup_empty_blocks(header_path, options):
568 """Clean up empty conditional blocks
569
570 Arguments:
571 header_path: path to the cleaned file.
572 options: option flags.
573 """
574 pattern = re.compile(r'^\s*#\s*if.*$\n^\s*#\s*endif.*$\n*', flags=re.M)
575 with open(header_path) as f:
576 data = f.read()
577
578 new_data = pattern.sub('\n', data)
579
580 show_diff(data.splitlines(True), new_data.splitlines(True), header_path,
581 options.color)
582
583 if options.dry_run:
584 return
585
586 with open(header_path, 'w') as f:
587 f.write(new_data)
588
Masahiro Yamadae9ea1222016-07-25 19:15:26 +0900589def cleanup_one_header(header_path, patterns, options):
Masahiro Yamada5a27c732015-05-20 11:36:07 +0900590 """Clean regex-matched lines away from a file.
591
592 Arguments:
593 header_path: path to the cleaned file.
594 patterns: list of regex patterns. Any lines matching to these
595 patterns are deleted.
Masahiro Yamadae9ea1222016-07-25 19:15:26 +0900596 options: option flags.
Masahiro Yamada5a27c732015-05-20 11:36:07 +0900597 """
598 with open(header_path) as f:
599 lines = f.readlines()
600
601 matched = []
602 for i, line in enumerate(lines):
Masahiro Yamadaa3a779f2016-07-25 19:15:27 +0900603 if i - 1 in matched and lines[i - 1][-2:] == '\\\n':
604 matched.append(i)
605 continue
Masahiro Yamada5a27c732015-05-20 11:36:07 +0900606 for pattern in patterns:
Masahiro Yamada8ba1f5d2016-07-25 19:15:24 +0900607 if pattern.search(line):
Masahiro Yamada5a27c732015-05-20 11:36:07 +0900608 matched.append(i)
609 break
610
Masahiro Yamada8ba1f5d2016-07-25 19:15:24 +0900611 if not matched:
612 return
613
614 # remove empty #ifdef ... #endif, successive blank lines
615 pattern_if = re.compile(r'#\s*if(def|ndef)?\W') # #if, #ifdef, #ifndef
616 pattern_elif = re.compile(r'#\s*el(if|se)\W') # #elif, #else
617 pattern_endif = re.compile(r'#\s*endif\W') # #endif
618 pattern_blank = re.compile(r'^\s*$') # empty line
619
620 while True:
621 old_matched = copy.copy(matched)
622 extend_matched_lines(lines, matched, [pattern_if],
623 [pattern_endif], True, True)
624 extend_matched_lines(lines, matched, [pattern_elif],
625 [pattern_elif, pattern_endif], True, False)
626 extend_matched_lines(lines, matched, [pattern_if, pattern_elif],
627 [pattern_blank], False, True)
628 extend_matched_lines(lines, matched, [pattern_blank],
629 [pattern_elif, pattern_endif], True, False)
630 extend_matched_lines(lines, matched, [pattern_blank],
631 [pattern_blank], True, False)
632 if matched == old_matched:
633 break
634
Masahiro Yamadaf2f69812016-07-25 19:15:25 +0900635 tolines = copy.copy(lines)
636
637 for i in reversed(matched):
638 tolines.pop(i)
639
Masahiro Yamadae9ea1222016-07-25 19:15:26 +0900640 show_diff(lines, tolines, header_path, options.color)
Masahiro Yamada8ba1f5d2016-07-25 19:15:24 +0900641
Masahiro Yamadae9ea1222016-07-25 19:15:26 +0900642 if options.dry_run:
Masahiro Yamada5a27c732015-05-20 11:36:07 +0900643 return
644
645 with open(header_path, 'w') as f:
Masahiro Yamadaf2f69812016-07-25 19:15:25 +0900646 for line in tolines:
647 f.write(line)
Masahiro Yamada5a27c732015-05-20 11:36:07 +0900648
Masahiro Yamadae9ea1222016-07-25 19:15:26 +0900649def cleanup_headers(configs, options):
Masahiro Yamada5a27c732015-05-20 11:36:07 +0900650 """Delete config defines from board headers.
651
652 Arguments:
Masahiro Yamadab134bc12016-05-19 15:51:57 +0900653 configs: A list of CONFIGs to remove.
Masahiro Yamadae9ea1222016-07-25 19:15:26 +0900654 options: option flags.
Masahiro Yamada5a27c732015-05-20 11:36:07 +0900655 """
Chris Packham85edfc12017-05-02 21:30:46 +1200656 if not confirm(options, 'Clean up headers?'):
657 return
Masahiro Yamada5a27c732015-05-20 11:36:07 +0900658
659 patterns = []
Masahiro Yamadab134bc12016-05-19 15:51:57 +0900660 for config in configs:
Masahiro Yamada5a27c732015-05-20 11:36:07 +0900661 patterns.append(re.compile(r'#\s*define\s+%s\W' % config))
662 patterns.append(re.compile(r'#\s*undef\s+%s\W' % config))
663
Joe Hershberger60727f52015-05-19 13:21:21 -0500664 for dir in 'include', 'arch', 'board':
665 for (dirpath, dirnames, filenames) in os.walk(dir):
Masahiro Yamadadc6de502016-07-25 19:15:22 +0900666 if dirpath == os.path.join('include', 'generated'):
667 continue
Joe Hershberger60727f52015-05-19 13:21:21 -0500668 for filename in filenames:
Tom Rini02b56702019-11-10 21:19:37 -0500669 if not filename.endswith(('~', '.dts', '.dtsi')):
Chris Packham4d9dbb12019-01-30 20:23:16 +1300670 header_path = os.path.join(dirpath, filename)
Tom Rini02b56702019-11-10 21:19:37 -0500671 # This file contains UTF-16 data and no CONFIG symbols
672 if header_path == 'include/video_font_data.h':
673 continue
Chris Packham4d9dbb12019-01-30 20:23:16 +1300674 cleanup_one_header(header_path, patterns, options)
675 cleanup_empty_blocks(header_path, options)
Masahiro Yamada5a27c732015-05-20 11:36:07 +0900676
Masahiro Yamada9ab02962016-07-25 19:15:29 +0900677def cleanup_one_extra_option(defconfig_path, configs, options):
678 """Delete config defines in CONFIG_SYS_EXTRA_OPTIONS in one defconfig file.
679
680 Arguments:
681 defconfig_path: path to the cleaned defconfig file.
682 configs: A list of CONFIGs to remove.
683 options: option flags.
684 """
685
686 start = 'CONFIG_SYS_EXTRA_OPTIONS="'
687 end = '"\n'
688
689 with open(defconfig_path) as f:
690 lines = f.readlines()
691
692 for i, line in enumerate(lines):
693 if line.startswith(start) and line.endswith(end):
694 break
695 else:
696 # CONFIG_SYS_EXTRA_OPTIONS was not found in this defconfig
697 return
698
699 old_tokens = line[len(start):-len(end)].split(',')
700 new_tokens = []
701
702 for token in old_tokens:
703 pos = token.find('=')
704 if not (token[:pos] if pos >= 0 else token) in configs:
705 new_tokens.append(token)
706
707 if new_tokens == old_tokens:
708 return
709
710 tolines = copy.copy(lines)
711
712 if new_tokens:
713 tolines[i] = start + ','.join(new_tokens) + end
714 else:
715 tolines.pop(i)
716
717 show_diff(lines, tolines, defconfig_path, options.color)
718
719 if options.dry_run:
720 return
721
722 with open(defconfig_path, 'w') as f:
723 for line in tolines:
724 f.write(line)
725
726def cleanup_extra_options(configs, options):
727 """Delete config defines in CONFIG_SYS_EXTRA_OPTIONS in defconfig files.
728
729 Arguments:
730 configs: A list of CONFIGs to remove.
731 options: option flags.
732 """
Chris Packham85edfc12017-05-02 21:30:46 +1200733 if not confirm(options, 'Clean up CONFIG_SYS_EXTRA_OPTIONS?'):
734 return
Masahiro Yamada9ab02962016-07-25 19:15:29 +0900735
736 configs = [ config[len('CONFIG_'):] for config in configs ]
737
738 defconfigs = get_all_defconfigs()
739
740 for defconfig in defconfigs:
741 cleanup_one_extra_option(os.path.join('configs', defconfig), configs,
742 options)
743
Chris Packhamca438342017-05-02 21:30:47 +1200744def cleanup_whitelist(configs, options):
745 """Delete config whitelist entries
746
747 Arguments:
748 configs: A list of CONFIGs to remove.
749 options: option flags.
750 """
751 if not confirm(options, 'Clean up whitelist entries?'):
752 return
753
754 with open(os.path.join('scripts', 'config_whitelist.txt')) as f:
755 lines = f.readlines()
756
757 lines = [x for x in lines if x.strip() not in configs]
758
759 with open(os.path.join('scripts', 'config_whitelist.txt'), 'w') as f:
760 f.write(''.join(lines))
761
Chris Packhamf90df592017-05-02 21:30:48 +1200762def find_matching(patterns, line):
763 for pat in patterns:
764 if pat.search(line):
765 return True
766 return False
767
768def cleanup_readme(configs, options):
769 """Delete config description in README
770
771 Arguments:
772 configs: A list of CONFIGs to remove.
773 options: option flags.
774 """
775 if not confirm(options, 'Clean up README?'):
776 return
777
778 patterns = []
779 for config in configs:
780 patterns.append(re.compile(r'^\s+%s' % config))
781
782 with open('README') as f:
783 lines = f.readlines()
784
785 found = False
786 newlines = []
787 for line in lines:
788 if not found:
789 found = find_matching(patterns, line)
790 if found:
791 continue
792
793 if found and re.search(r'^\s+CONFIG', line):
794 found = False
795
796 if not found:
797 newlines.append(line)
798
799 with open('README', 'w') as f:
800 f.write(''.join(newlines))
801
Markus Klotzbuecherb237d352019-05-15 15:15:52 +0200802def try_expand(line):
803 """If value looks like an expression, try expanding it
804 Otherwise just return the existing value
805 """
806 if line.find('=') == -1:
807 return line
808
809 try:
Markus Klotzbuecherb3192f42020-02-12 20:46:44 +0100810 aeval = asteval.Interpreter( usersyms=SIZES, minimal=True )
Markus Klotzbuecherb237d352019-05-15 15:15:52 +0200811 cfg, val = re.split("=", line)
812 val= val.strip('\"')
813 if re.search("[*+-/]|<<|SZ_+|\(([^\)]+)\)", val):
Markus Klotzbuecherb3192f42020-02-12 20:46:44 +0100814 newval = hex(aeval(val))
Simon Glass793dca32019-10-31 07:42:57 -0600815 print("\tExpanded expression %s to %s" % (val, newval))
Markus Klotzbuecherb237d352019-05-15 15:15:52 +0200816 return cfg+'='+newval
817 except:
Simon Glass793dca32019-10-31 07:42:57 -0600818 print("\tFailed to expand expression in %s" % line)
Markus Klotzbuecherb237d352019-05-15 15:15:52 +0200819
820 return line
821
Chris Packhamca438342017-05-02 21:30:47 +1200822
Masahiro Yamada5a27c732015-05-20 11:36:07 +0900823### classes ###
Masahiro Yamadac5e60fd2016-05-19 15:51:55 +0900824class Progress:
825
826 """Progress Indicator"""
827
828 def __init__(self, total):
829 """Create a new progress indicator.
830
831 Arguments:
832 total: A number of defconfig files to process.
833 """
834 self.current = 0
835 self.total = total
836
837 def inc(self):
838 """Increment the number of processed defconfig files."""
839
840 self.current += 1
841
842 def show(self):
843 """Display the progress."""
Simon Glass793dca32019-10-31 07:42:57 -0600844 print(' %d defconfigs out of %d\r' % (self.current, self.total), end=' ')
Masahiro Yamadac5e60fd2016-05-19 15:51:55 +0900845 sys.stdout.flush()
846
Simon Glasscb008832017-06-15 21:39:33 -0600847
848class KconfigScanner:
849 """Kconfig scanner."""
850
851 def __init__(self):
852 """Scan all the Kconfig files and create a Config object."""
853 # Define environment variables referenced from Kconfig
854 os.environ['srctree'] = os.getcwd()
855 os.environ['UBOOTVERSION'] = 'dummy'
856 os.environ['KCONFIG_OBJDIR'] = ''
Tom Rini65e05dd2019-09-20 17:42:09 -0400857 self.conf = kconfiglib.Kconfig()
Simon Glasscb008832017-06-15 21:39:33 -0600858
859
Masahiro Yamada5a27c732015-05-20 11:36:07 +0900860class KconfigParser:
861
862 """A parser of .config and include/autoconf.mk."""
863
864 re_arch = re.compile(r'CONFIG_SYS_ARCH="(.*)"')
865 re_cpu = re.compile(r'CONFIG_SYS_CPU="(.*)"')
866
Masahiro Yamada522e8dc2016-05-19 15:52:01 +0900867 def __init__(self, configs, options, build_dir):
Masahiro Yamada5a27c732015-05-20 11:36:07 +0900868 """Create a new parser.
869
870 Arguments:
Masahiro Yamadab134bc12016-05-19 15:51:57 +0900871 configs: A list of CONFIGs to move.
Masahiro Yamada5a27c732015-05-20 11:36:07 +0900872 options: option flags.
873 build_dir: Build directory.
874 """
Masahiro Yamadab134bc12016-05-19 15:51:57 +0900875 self.configs = configs
Masahiro Yamada5a27c732015-05-20 11:36:07 +0900876 self.options = options
Masahiro Yamada1f169922016-05-19 15:52:00 +0900877 self.dotconfig = os.path.join(build_dir, '.config')
878 self.autoconf = os.path.join(build_dir, 'include', 'autoconf.mk')
Masahiro Yamada07913d12016-08-22 22:18:22 +0900879 self.spl_autoconf = os.path.join(build_dir, 'spl', 'include',
880 'autoconf.mk')
Simon Glassf3b8e642017-06-01 19:39:01 -0600881 self.config_autoconf = os.path.join(build_dir, AUTO_CONF_PATH)
Masahiro Yamada5da4f852016-05-19 15:52:06 +0900882 self.defconfig = os.path.join(build_dir, 'defconfig')
Masahiro Yamada5a27c732015-05-20 11:36:07 +0900883
Simon Glass6821a742017-07-10 14:47:47 -0600884 def get_arch(self):
885 """Parse .config file and return the architecture.
Masahiro Yamada5a27c732015-05-20 11:36:07 +0900886
887 Returns:
Simon Glass6821a742017-07-10 14:47:47 -0600888 Architecture name (e.g. 'arm').
Masahiro Yamada5a27c732015-05-20 11:36:07 +0900889 """
890 arch = ''
891 cpu = ''
Masahiro Yamada1f169922016-05-19 15:52:00 +0900892 for line in open(self.dotconfig):
Masahiro Yamada5a27c732015-05-20 11:36:07 +0900893 m = self.re_arch.match(line)
894 if m:
895 arch = m.group(1)
896 continue
897 m = self.re_cpu.match(line)
898 if m:
899 cpu = m.group(1)
900
Masahiro Yamada90ed6cb2016-05-19 15:51:53 +0900901 if not arch:
902 return None
Masahiro Yamada5a27c732015-05-20 11:36:07 +0900903
904 # fix-up for aarch64
905 if arch == 'arm' and cpu == 'armv8':
906 arch = 'aarch64'
907
Simon Glass6821a742017-07-10 14:47:47 -0600908 return arch
Masahiro Yamada5a27c732015-05-20 11:36:07 +0900909
Masahiro Yamadab134bc12016-05-19 15:51:57 +0900910 def parse_one_config(self, config, dotconfig_lines, autoconf_lines):
Masahiro Yamada5a27c732015-05-20 11:36:07 +0900911 """Parse .config, defconfig, include/autoconf.mk for one config.
912
913 This function looks for the config options in the lines from
914 defconfig, .config, and include/autoconf.mk in order to decide
915 which action should be taken for this defconfig.
916
917 Arguments:
Masahiro Yamadab134bc12016-05-19 15:51:57 +0900918 config: CONFIG name to parse.
Masahiro Yamadacc008292016-05-19 15:51:56 +0900919 dotconfig_lines: lines from the .config file.
Masahiro Yamada5a27c732015-05-20 11:36:07 +0900920 autoconf_lines: lines from the include/autoconf.mk file.
921
922 Returns:
923 A tupple of the action for this defconfig and the line
924 matched for the config.
925 """
Masahiro Yamada5a27c732015-05-20 11:36:07 +0900926 not_set = '# %s is not set' % config
927
Masahiro Yamada5a27c732015-05-20 11:36:07 +0900928 for line in autoconf_lines:
929 line = line.rstrip()
930 if line.startswith(config + '='):
Masahiro Yamadacc008292016-05-19 15:51:56 +0900931 new_val = line
Masahiro Yamada5a27c732015-05-20 11:36:07 +0900932 break
Masahiro Yamada5a27c732015-05-20 11:36:07 +0900933 else:
Masahiro Yamadacc008292016-05-19 15:51:56 +0900934 new_val = not_set
Masahiro Yamada5a27c732015-05-20 11:36:07 +0900935
Markus Klotzbuecherb237d352019-05-15 15:15:52 +0200936 new_val = try_expand(new_val)
937
Masahiro Yamada916224c2016-08-22 22:18:21 +0900938 for line in dotconfig_lines:
939 line = line.rstrip()
940 if line.startswith(config + '=') or line == not_set:
941 old_val = line
942 break
943 else:
944 if new_val == not_set:
945 return (ACTION_NO_ENTRY, config)
946 else:
947 return (ACTION_NO_ENTRY_WARN, config)
948
Masahiro Yamadacc008292016-05-19 15:51:56 +0900949 # If this CONFIG is neither bool nor trisate
950 if old_val[-2:] != '=y' and old_val[-2:] != '=m' and old_val != not_set:
951 # tools/scripts/define2mk.sed changes '1' to 'y'.
952 # This is a problem if the CONFIG is int type.
953 # Check the type in Kconfig and handle it correctly.
954 if new_val[-2:] == '=y':
955 new_val = new_val[:-1] + '1'
956
Masahiro Yamada50301592016-06-15 14:33:50 +0900957 return (ACTION_NO_CHANGE if old_val == new_val else ACTION_MOVE,
958 new_val)
Masahiro Yamada5a27c732015-05-20 11:36:07 +0900959
Masahiro Yamada1d085562016-05-19 15:52:02 +0900960 def update_dotconfig(self):
Masahiro Yamada6ff36d22016-05-19 15:51:50 +0900961 """Parse files for the config options and update the .config.
Masahiro Yamada5a27c732015-05-20 11:36:07 +0900962
Masahiro Yamadacc008292016-05-19 15:51:56 +0900963 This function parses the generated .config and include/autoconf.mk
964 searching the target options.
Masahiro Yamada6ff36d22016-05-19 15:51:50 +0900965 Move the config option(s) to the .config as needed.
Masahiro Yamada5a27c732015-05-20 11:36:07 +0900966
967 Arguments:
968 defconfig: defconfig name.
Masahiro Yamada522e8dc2016-05-19 15:52:01 +0900969
970 Returns:
Masahiro Yamada7fb0bac2016-05-19 15:52:04 +0900971 Return a tuple of (updated flag, log string).
972 The "updated flag" is True if the .config was updated, False
973 otherwise. The "log string" shows what happend to the .config.
Masahiro Yamada5a27c732015-05-20 11:36:07 +0900974 """
975
Masahiro Yamada5a27c732015-05-20 11:36:07 +0900976 results = []
Masahiro Yamada7fb0bac2016-05-19 15:52:04 +0900977 updated = False
Masahiro Yamada916224c2016-08-22 22:18:21 +0900978 suspicious = False
Masahiro Yamada07913d12016-08-22 22:18:22 +0900979 rm_files = [self.config_autoconf, self.autoconf]
980
981 if self.options.spl:
982 if os.path.exists(self.spl_autoconf):
983 autoconf_path = self.spl_autoconf
984 rm_files.append(self.spl_autoconf)
985 else:
986 for f in rm_files:
987 os.remove(f)
988 return (updated, suspicious,
989 color_text(self.options.color, COLOR_BROWN,
990 "SPL is not enabled. Skipped.") + '\n')
991 else:
992 autoconf_path = self.autoconf
Masahiro Yamada5a27c732015-05-20 11:36:07 +0900993
Masahiro Yamada1f169922016-05-19 15:52:00 +0900994 with open(self.dotconfig) as f:
Masahiro Yamadacc008292016-05-19 15:51:56 +0900995 dotconfig_lines = f.readlines()
Masahiro Yamada5a27c732015-05-20 11:36:07 +0900996
Masahiro Yamada07913d12016-08-22 22:18:22 +0900997 with open(autoconf_path) as f:
Masahiro Yamada5a27c732015-05-20 11:36:07 +0900998 autoconf_lines = f.readlines()
999
Masahiro Yamadab134bc12016-05-19 15:51:57 +09001000 for config in self.configs:
1001 result = self.parse_one_config(config, dotconfig_lines,
Joe Hershberger96464ba2015-05-19 13:21:17 -05001002 autoconf_lines)
Masahiro Yamada5a27c732015-05-20 11:36:07 +09001003 results.append(result)
1004
1005 log = ''
1006
1007 for (action, value) in results:
1008 if action == ACTION_MOVE:
1009 actlog = "Move '%s'" % value
1010 log_color = COLOR_LIGHT_GREEN
Masahiro Yamadacc008292016-05-19 15:51:56 +09001011 elif action == ACTION_NO_ENTRY:
1012 actlog = "%s is not defined in Kconfig. Do nothing." % value
Masahiro Yamada5a27c732015-05-20 11:36:07 +09001013 log_color = COLOR_LIGHT_BLUE
Masahiro Yamada916224c2016-08-22 22:18:21 +09001014 elif action == ACTION_NO_ENTRY_WARN:
1015 actlog = "%s is not defined in Kconfig (suspicious). Do nothing." % value
1016 log_color = COLOR_YELLOW
1017 suspicious = True
Masahiro Yamadacc008292016-05-19 15:51:56 +09001018 elif action == ACTION_NO_CHANGE:
1019 actlog = "'%s' is the same as the define in Kconfig. Do nothing." \
1020 % value
Masahiro Yamada5a27c732015-05-20 11:36:07 +09001021 log_color = COLOR_LIGHT_PURPLE
Masahiro Yamada07913d12016-08-22 22:18:22 +09001022 elif action == ACTION_SPL_NOT_EXIST:
1023 actlog = "SPL is not enabled for this defconfig. Skip."
1024 log_color = COLOR_PURPLE
Masahiro Yamada5a27c732015-05-20 11:36:07 +09001025 else:
1026 sys.exit("Internal Error. This should not happen.")
1027
Masahiro Yamada1d085562016-05-19 15:52:02 +09001028 log += color_text(self.options.color, log_color, actlog) + '\n'
Masahiro Yamada5a27c732015-05-20 11:36:07 +09001029
Masahiro Yamada1f169922016-05-19 15:52:00 +09001030 with open(self.dotconfig, 'a') as f:
Masahiro Yamadae423d172016-05-19 15:51:49 +09001031 for (action, value) in results:
1032 if action == ACTION_MOVE:
1033 f.write(value + '\n')
Masahiro Yamada7fb0bac2016-05-19 15:52:04 +09001034 updated = True
Masahiro Yamada5a27c732015-05-20 11:36:07 +09001035
Masahiro Yamada5da4f852016-05-19 15:52:06 +09001036 self.results = results
Masahiro Yamada07913d12016-08-22 22:18:22 +09001037 for f in rm_files:
1038 os.remove(f)
Masahiro Yamada5a27c732015-05-20 11:36:07 +09001039
Masahiro Yamada916224c2016-08-22 22:18:21 +09001040 return (updated, suspicious, log)
Masahiro Yamada522e8dc2016-05-19 15:52:01 +09001041
Masahiro Yamada5da4f852016-05-19 15:52:06 +09001042 def check_defconfig(self):
1043 """Check the defconfig after savedefconfig
1044
1045 Returns:
1046 Return additional log if moved CONFIGs were removed again by
1047 'make savedefconfig'.
1048 """
1049
1050 log = ''
1051
1052 with open(self.defconfig) as f:
1053 defconfig_lines = f.readlines()
1054
1055 for (action, value) in self.results:
1056 if action != ACTION_MOVE:
1057 continue
1058 if not value + '\n' in defconfig_lines:
1059 log += color_text(self.options.color, COLOR_YELLOW,
1060 "'%s' was removed by savedefconfig.\n" %
1061 value)
1062
1063 return log
1064
Simon Glassd73fcb12017-06-01 19:39:02 -06001065
1066class DatabaseThread(threading.Thread):
1067 """This thread processes results from Slot threads.
1068
1069 It collects the data in the master config directary. There is only one
1070 result thread, and this helps to serialise the build output.
1071 """
1072 def __init__(self, config_db, db_queue):
1073 """Set up a new result thread
1074
1075 Args:
1076 builder: Builder which will be sent each result
1077 """
1078 threading.Thread.__init__(self)
1079 self.config_db = config_db
1080 self.db_queue= db_queue
1081
1082 def run(self):
1083 """Called to start up the result thread.
1084
1085 We collect the next result job and pass it on to the build.
1086 """
1087 while True:
1088 defconfig, configs = self.db_queue.get()
1089 self.config_db[defconfig] = configs
1090 self.db_queue.task_done()
1091
1092
Masahiro Yamada5a27c732015-05-20 11:36:07 +09001093class Slot:
1094
1095 """A slot to store a subprocess.
1096
1097 Each instance of this class handles one subprocess.
1098 This class is useful to control multiple threads
1099 for faster processing.
1100 """
1101
Simon Glass6821a742017-07-10 14:47:47 -06001102 def __init__(self, toolchains, configs, options, progress, devnull,
1103 make_cmd, reference_src_dir, db_queue):
Masahiro Yamada5a27c732015-05-20 11:36:07 +09001104 """Create a new process slot.
1105
1106 Arguments:
Simon Glass6821a742017-07-10 14:47:47 -06001107 toolchains: Toolchains object containing toolchains.
Masahiro Yamadab134bc12016-05-19 15:51:57 +09001108 configs: A list of CONFIGs to move.
Masahiro Yamada5a27c732015-05-20 11:36:07 +09001109 options: option flags.
Masahiro Yamadac5e60fd2016-05-19 15:51:55 +09001110 progress: A progress indicator.
Masahiro Yamada5a27c732015-05-20 11:36:07 +09001111 devnull: A file object of '/dev/null'.
1112 make_cmd: command name of GNU Make.
Joe Hershberger6b96c1a2016-06-10 14:53:32 -05001113 reference_src_dir: Determine the true starting config state from this
1114 source tree.
Simon Glassd73fcb12017-06-01 19:39:02 -06001115 db_queue: output queue to write config info for the database
Masahiro Yamada5a27c732015-05-20 11:36:07 +09001116 """
Simon Glass6821a742017-07-10 14:47:47 -06001117 self.toolchains = toolchains
Masahiro Yamada5a27c732015-05-20 11:36:07 +09001118 self.options = options
Masahiro Yamadac5e60fd2016-05-19 15:51:55 +09001119 self.progress = progress
Masahiro Yamada5a27c732015-05-20 11:36:07 +09001120 self.build_dir = tempfile.mkdtemp()
1121 self.devnull = devnull
1122 self.make_cmd = (make_cmd, 'O=' + self.build_dir)
Joe Hershberger6b96c1a2016-06-10 14:53:32 -05001123 self.reference_src_dir = reference_src_dir
Simon Glassd73fcb12017-06-01 19:39:02 -06001124 self.db_queue = db_queue
Masahiro Yamada522e8dc2016-05-19 15:52:01 +09001125 self.parser = KconfigParser(configs, options, self.build_dir)
Masahiro Yamada5a27c732015-05-20 11:36:07 +09001126 self.state = STATE_IDLE
Masahiro Yamada09c6c062016-08-22 22:18:20 +09001127 self.failed_boards = set()
1128 self.suspicious_boards = set()
Masahiro Yamada5a27c732015-05-20 11:36:07 +09001129
1130 def __del__(self):
1131 """Delete the working directory
1132
1133 This function makes sure the temporary directory is cleaned away
1134 even if Python suddenly dies due to error. It should be done in here
Joe Hershbergerf2dae752016-06-10 14:53:29 -05001135 because it is guaranteed the destructor is always invoked when the
Masahiro Yamada5a27c732015-05-20 11:36:07 +09001136 instance of the class gets unreferenced.
1137
1138 If the subprocess is still running, wait until it finishes.
1139 """
1140 if self.state != STATE_IDLE:
1141 while self.ps.poll() == None:
1142 pass
1143 shutil.rmtree(self.build_dir)
1144
Masahiro Yamadac5e60fd2016-05-19 15:51:55 +09001145 def add(self, defconfig):
Masahiro Yamada5a27c732015-05-20 11:36:07 +09001146 """Assign a new subprocess for defconfig and add it to the slot.
1147
1148 If the slot is vacant, create a new subprocess for processing the
1149 given defconfig and add it to the slot. Just returns False if
1150 the slot is occupied (i.e. the current subprocess is still running).
1151
1152 Arguments:
1153 defconfig: defconfig name.
1154
1155 Returns:
1156 Return True on success or False on failure
1157 """
1158 if self.state != STATE_IDLE:
1159 return False
Masahiro Yamadae307fa92016-06-08 11:47:37 +09001160
Masahiro Yamada5a27c732015-05-20 11:36:07 +09001161 self.defconfig = defconfig
Masahiro Yamada1d085562016-05-19 15:52:02 +09001162 self.log = ''
Masahiro Yamadaf432c332016-06-15 14:33:52 +09001163 self.current_src_dir = self.reference_src_dir
Masahiro Yamadae307fa92016-06-08 11:47:37 +09001164 self.do_defconfig()
Masahiro Yamada5a27c732015-05-20 11:36:07 +09001165 return True
1166
1167 def poll(self):
1168 """Check the status of the subprocess and handle it as needed.
1169
1170 Returns True if the slot is vacant (i.e. in idle state).
1171 If the configuration is successfully finished, assign a new
1172 subprocess to build include/autoconf.mk.
1173 If include/autoconf.mk is generated, invoke the parser to
Masahiro Yamada7fb0bac2016-05-19 15:52:04 +09001174 parse the .config and the include/autoconf.mk, moving
1175 config options to the .config as needed.
1176 If the .config was updated, run "make savedefconfig" to sync
1177 it, update the original defconfig, and then set the slot back
1178 to the idle state.
Masahiro Yamada5a27c732015-05-20 11:36:07 +09001179
1180 Returns:
1181 Return True if the subprocess is terminated, False otherwise
1182 """
1183 if self.state == STATE_IDLE:
1184 return True
1185
1186 if self.ps.poll() == None:
1187 return False
1188
1189 if self.ps.poll() != 0:
Masahiro Yamadae307fa92016-06-08 11:47:37 +09001190 self.handle_error()
1191 elif self.state == STATE_DEFCONFIG:
Masahiro Yamadaf432c332016-06-15 14:33:52 +09001192 if self.reference_src_dir and not self.current_src_dir:
Joe Hershberger6b96c1a2016-06-10 14:53:32 -05001193 self.do_savedefconfig()
1194 else:
1195 self.do_autoconf()
Masahiro Yamadae307fa92016-06-08 11:47:37 +09001196 elif self.state == STATE_AUTOCONF:
Masahiro Yamadaf432c332016-06-15 14:33:52 +09001197 if self.current_src_dir:
1198 self.current_src_dir = None
Joe Hershberger6b96c1a2016-06-10 14:53:32 -05001199 self.do_defconfig()
Simon Glassd73fcb12017-06-01 19:39:02 -06001200 elif self.options.build_db:
1201 self.do_build_db()
Joe Hershberger6b96c1a2016-06-10 14:53:32 -05001202 else:
1203 self.do_savedefconfig()
Masahiro Yamadae307fa92016-06-08 11:47:37 +09001204 elif self.state == STATE_SAVEDEFCONFIG:
1205 self.update_defconfig()
1206 else:
1207 sys.exit("Internal Error. This should not happen.")
Masahiro Yamada5a27c732015-05-20 11:36:07 +09001208
Masahiro Yamadae307fa92016-06-08 11:47:37 +09001209 return True if self.state == STATE_IDLE else False
Joe Hershberger96464ba2015-05-19 13:21:17 -05001210
Masahiro Yamadae307fa92016-06-08 11:47:37 +09001211 def handle_error(self):
1212 """Handle error cases."""
Masahiro Yamada8513dc02016-05-19 15:52:08 +09001213
Masahiro Yamadae307fa92016-06-08 11:47:37 +09001214 self.log += color_text(self.options.color, COLOR_LIGHT_RED,
1215 "Failed to process.\n")
1216 if self.options.verbose:
1217 self.log += color_text(self.options.color, COLOR_LIGHT_CYAN,
Markus Klotzbuecher4f5c5e92020-02-12 20:46:45 +01001218 self.ps.stderr.read().decode())
Masahiro Yamadae307fa92016-06-08 11:47:37 +09001219 self.finish(False)
Joe Hershberger96464ba2015-05-19 13:21:17 -05001220
Masahiro Yamadae307fa92016-06-08 11:47:37 +09001221 def do_defconfig(self):
1222 """Run 'make <board>_defconfig' to create the .config file."""
Masahiro Yamadac8e1b102016-05-19 15:52:07 +09001223
Masahiro Yamadae307fa92016-06-08 11:47:37 +09001224 cmd = list(self.make_cmd)
1225 cmd.append(self.defconfig)
1226 self.ps = subprocess.Popen(cmd, stdout=self.devnull,
Masahiro Yamadaf432c332016-06-15 14:33:52 +09001227 stderr=subprocess.PIPE,
1228 cwd=self.current_src_dir)
Masahiro Yamadae307fa92016-06-08 11:47:37 +09001229 self.state = STATE_DEFCONFIG
Masahiro Yamadac8e1b102016-05-19 15:52:07 +09001230
Masahiro Yamadae307fa92016-06-08 11:47:37 +09001231 def do_autoconf(self):
Simon Glassf3b8e642017-06-01 19:39:01 -06001232 """Run 'make AUTO_CONF_PATH'."""
Masahiro Yamada5a27c732015-05-20 11:36:07 +09001233
Simon Glass6821a742017-07-10 14:47:47 -06001234 arch = self.parser.get_arch()
1235 try:
1236 toolchain = self.toolchains.Select(arch)
1237 except ValueError:
Masahiro Yamada1d085562016-05-19 15:52:02 +09001238 self.log += color_text(self.options.color, COLOR_YELLOW,
Chris Packhamce3ba452017-08-27 20:00:51 +12001239 "Tool chain for '%s' is missing. Do nothing.\n" % arch)
Masahiro Yamada4efef992016-05-19 15:52:03 +09001240 self.finish(False)
Masahiro Yamadae307fa92016-06-08 11:47:37 +09001241 return
Simon Glass793dca32019-10-31 07:42:57 -06001242 env = toolchain.MakeEnvironment(False)
Masahiro Yamada90ed6cb2016-05-19 15:51:53 +09001243
Masahiro Yamada5a27c732015-05-20 11:36:07 +09001244 cmd = list(self.make_cmd)
Joe Hershberger7740f652015-05-19 13:21:18 -05001245 cmd.append('KCONFIG_IGNORE_DUPLICATES=1')
Simon Glassf3b8e642017-06-01 19:39:01 -06001246 cmd.append(AUTO_CONF_PATH)
Simon Glass6821a742017-07-10 14:47:47 -06001247 self.ps = subprocess.Popen(cmd, stdout=self.devnull, env=env,
Masahiro Yamadaf432c332016-06-15 14:33:52 +09001248 stderr=subprocess.PIPE,
1249 cwd=self.current_src_dir)
Masahiro Yamada5a27c732015-05-20 11:36:07 +09001250 self.state = STATE_AUTOCONF
Masahiro Yamadae307fa92016-06-08 11:47:37 +09001251
Simon Glassd73fcb12017-06-01 19:39:02 -06001252 def do_build_db(self):
1253 """Add the board to the database"""
1254 configs = {}
1255 with open(os.path.join(self.build_dir, AUTO_CONF_PATH)) as fd:
1256 for line in fd.readlines():
1257 if line.startswith('CONFIG'):
1258 config, value = line.split('=', 1)
1259 configs[config] = value.rstrip()
1260 self.db_queue.put([self.defconfig, configs])
1261 self.finish(True)
1262
Masahiro Yamadae307fa92016-06-08 11:47:37 +09001263 def do_savedefconfig(self):
1264 """Update the .config and run 'make savedefconfig'."""
1265
Masahiro Yamada916224c2016-08-22 22:18:21 +09001266 (updated, suspicious, log) = self.parser.update_dotconfig()
1267 if suspicious:
1268 self.suspicious_boards.add(self.defconfig)
Masahiro Yamadae307fa92016-06-08 11:47:37 +09001269 self.log += log
1270
1271 if not self.options.force_sync and not updated:
1272 self.finish(True)
1273 return
1274 if updated:
1275 self.log += color_text(self.options.color, COLOR_LIGHT_GREEN,
1276 "Syncing by savedefconfig...\n")
1277 else:
1278 self.log += "Syncing by savedefconfig (forced by option)...\n"
1279
1280 cmd = list(self.make_cmd)
1281 cmd.append('savedefconfig')
1282 self.ps = subprocess.Popen(cmd, stdout=self.devnull,
1283 stderr=subprocess.PIPE)
1284 self.state = STATE_SAVEDEFCONFIG
1285
1286 def update_defconfig(self):
1287 """Update the input defconfig and go back to the idle state."""
1288
Masahiro Yamadafc2661e2016-06-15 14:33:54 +09001289 log = self.parser.check_defconfig()
1290 if log:
Masahiro Yamada09c6c062016-08-22 22:18:20 +09001291 self.suspicious_boards.add(self.defconfig)
Masahiro Yamadafc2661e2016-06-15 14:33:54 +09001292 self.log += log
Masahiro Yamadae307fa92016-06-08 11:47:37 +09001293 orig_defconfig = os.path.join('configs', self.defconfig)
1294 new_defconfig = os.path.join(self.build_dir, 'defconfig')
1295 updated = not filecmp.cmp(orig_defconfig, new_defconfig)
1296
1297 if updated:
Joe Hershberger06cc1d32016-06-10 14:53:30 -05001298 self.log += color_text(self.options.color, COLOR_LIGHT_BLUE,
Masahiro Yamadae307fa92016-06-08 11:47:37 +09001299 "defconfig was updated.\n")
1300
1301 if not self.options.dry_run and updated:
1302 shutil.move(new_defconfig, orig_defconfig)
1303 self.finish(True)
Masahiro Yamada5a27c732015-05-20 11:36:07 +09001304
Masahiro Yamada4efef992016-05-19 15:52:03 +09001305 def finish(self, success):
1306 """Display log along with progress and go to the idle state.
Masahiro Yamada1d085562016-05-19 15:52:02 +09001307
1308 Arguments:
Masahiro Yamada4efef992016-05-19 15:52:03 +09001309 success: Should be True when the defconfig was processed
1310 successfully, or False when it fails.
Masahiro Yamada1d085562016-05-19 15:52:02 +09001311 """
1312 # output at least 30 characters to hide the "* defconfigs out of *".
1313 log = self.defconfig.ljust(30) + '\n'
1314
1315 log += '\n'.join([ ' ' + s for s in self.log.split('\n') ])
1316 # Some threads are running in parallel.
1317 # Print log atomically to not mix up logs from different threads.
Simon Glass793dca32019-10-31 07:42:57 -06001318 print(log, file=(sys.stdout if success else sys.stderr))
Masahiro Yamada4efef992016-05-19 15:52:03 +09001319
1320 if not success:
1321 if self.options.exit_on_error:
1322 sys.exit("Exit on error.")
1323 # If --exit-on-error flag is not set, skip this board and continue.
1324 # Record the failed board.
Masahiro Yamada09c6c062016-08-22 22:18:20 +09001325 self.failed_boards.add(self.defconfig)
Masahiro Yamada4efef992016-05-19 15:52:03 +09001326
Masahiro Yamada1d085562016-05-19 15:52:02 +09001327 self.progress.inc()
1328 self.progress.show()
Masahiro Yamada4efef992016-05-19 15:52:03 +09001329 self.state = STATE_IDLE
Masahiro Yamada1d085562016-05-19 15:52:02 +09001330
Masahiro Yamada5a27c732015-05-20 11:36:07 +09001331 def get_failed_boards(self):
Masahiro Yamada09c6c062016-08-22 22:18:20 +09001332 """Returns a set of failed boards (defconfigs) in this slot.
Masahiro Yamada5a27c732015-05-20 11:36:07 +09001333 """
1334 return self.failed_boards
1335
Masahiro Yamadafc2661e2016-06-15 14:33:54 +09001336 def get_suspicious_boards(self):
Masahiro Yamada09c6c062016-08-22 22:18:20 +09001337 """Returns a set of boards (defconfigs) with possible misconversion.
Masahiro Yamadafc2661e2016-06-15 14:33:54 +09001338 """
Masahiro Yamada916224c2016-08-22 22:18:21 +09001339 return self.suspicious_boards - self.failed_boards
Masahiro Yamadafc2661e2016-06-15 14:33:54 +09001340
Masahiro Yamada5a27c732015-05-20 11:36:07 +09001341class Slots:
1342
1343 """Controller of the array of subprocess slots."""
1344
Simon Glass6821a742017-07-10 14:47:47 -06001345 def __init__(self, toolchains, configs, options, progress,
1346 reference_src_dir, db_queue):
Masahiro Yamada5a27c732015-05-20 11:36:07 +09001347 """Create a new slots controller.
1348
1349 Arguments:
Simon Glass6821a742017-07-10 14:47:47 -06001350 toolchains: Toolchains object containing toolchains.
Masahiro Yamadab134bc12016-05-19 15:51:57 +09001351 configs: A list of CONFIGs to move.
Masahiro Yamada5a27c732015-05-20 11:36:07 +09001352 options: option flags.
Masahiro Yamadac5e60fd2016-05-19 15:51:55 +09001353 progress: A progress indicator.
Joe Hershberger6b96c1a2016-06-10 14:53:32 -05001354 reference_src_dir: Determine the true starting config state from this
1355 source tree.
Simon Glassd73fcb12017-06-01 19:39:02 -06001356 db_queue: output queue to write config info for the database
Masahiro Yamada5a27c732015-05-20 11:36:07 +09001357 """
1358 self.options = options
1359 self.slots = []
1360 devnull = get_devnull()
1361 make_cmd = get_make_cmd()
1362 for i in range(options.jobs):
Simon Glass6821a742017-07-10 14:47:47 -06001363 self.slots.append(Slot(toolchains, configs, options, progress,
1364 devnull, make_cmd, reference_src_dir,
1365 db_queue))
Masahiro Yamada5a27c732015-05-20 11:36:07 +09001366
Masahiro Yamadac5e60fd2016-05-19 15:51:55 +09001367 def add(self, defconfig):
Masahiro Yamada5a27c732015-05-20 11:36:07 +09001368 """Add a new subprocess if a vacant slot is found.
1369
1370 Arguments:
1371 defconfig: defconfig name to be put into.
1372
1373 Returns:
1374 Return True on success or False on failure
1375 """
1376 for slot in self.slots:
Masahiro Yamadac5e60fd2016-05-19 15:51:55 +09001377 if slot.add(defconfig):
Masahiro Yamada5a27c732015-05-20 11:36:07 +09001378 return True
1379 return False
1380
1381 def available(self):
1382 """Check if there is a vacant slot.
1383
1384 Returns:
1385 Return True if at lease one vacant slot is found, False otherwise.
1386 """
1387 for slot in self.slots:
1388 if slot.poll():
1389 return True
1390 return False
1391
1392 def empty(self):
1393 """Check if all slots are vacant.
1394
1395 Returns:
1396 Return True if all the slots are vacant, False otherwise.
1397 """
1398 ret = True
1399 for slot in self.slots:
1400 if not slot.poll():
1401 ret = False
1402 return ret
1403
1404 def show_failed_boards(self):
1405 """Display all of the failed boards (defconfigs)."""
Masahiro Yamada09c6c062016-08-22 22:18:20 +09001406 boards = set()
Masahiro Yamada96dccd92016-06-15 14:33:53 +09001407 output_file = 'moveconfig.failed'
Masahiro Yamada5a27c732015-05-20 11:36:07 +09001408
1409 for slot in self.slots:
Masahiro Yamada09c6c062016-08-22 22:18:20 +09001410 boards |= slot.get_failed_boards()
Masahiro Yamada5a27c732015-05-20 11:36:07 +09001411
Masahiro Yamada96dccd92016-06-15 14:33:53 +09001412 if boards:
1413 boards = '\n'.join(boards) + '\n'
1414 msg = "The following boards were not processed due to error:\n"
1415 msg += boards
1416 msg += "(the list has been saved in %s)\n" % output_file
Simon Glass793dca32019-10-31 07:42:57 -06001417 print(color_text(self.options.color, COLOR_LIGHT_RED,
1418 msg), file=sys.stderr)
Masahiro Yamada5a27c732015-05-20 11:36:07 +09001419
Masahiro Yamada96dccd92016-06-15 14:33:53 +09001420 with open(output_file, 'w') as f:
1421 f.write(boards)
Joe Hershberger2559cd82015-05-19 13:21:22 -05001422
Masahiro Yamadafc2661e2016-06-15 14:33:54 +09001423 def show_suspicious_boards(self):
1424 """Display all boards (defconfigs) with possible misconversion."""
Masahiro Yamada09c6c062016-08-22 22:18:20 +09001425 boards = set()
Masahiro Yamadafc2661e2016-06-15 14:33:54 +09001426 output_file = 'moveconfig.suspicious'
1427
1428 for slot in self.slots:
Masahiro Yamada09c6c062016-08-22 22:18:20 +09001429 boards |= slot.get_suspicious_boards()
Masahiro Yamadafc2661e2016-06-15 14:33:54 +09001430
1431 if boards:
1432 boards = '\n'.join(boards) + '\n'
1433 msg = "The following boards might have been converted incorrectly.\n"
1434 msg += "It is highly recommended to check them manually:\n"
1435 msg += boards
1436 msg += "(the list has been saved in %s)\n" % output_file
Simon Glass793dca32019-10-31 07:42:57 -06001437 print(color_text(self.options.color, COLOR_YELLOW,
1438 msg), file=sys.stderr)
Masahiro Yamadafc2661e2016-06-15 14:33:54 +09001439
1440 with open(output_file, 'w') as f:
1441 f.write(boards)
1442
Masahiro Yamada5cc42a52016-06-15 14:33:51 +09001443class ReferenceSource:
1444
1445 """Reference source against which original configs should be parsed."""
1446
1447 def __init__(self, commit):
1448 """Create a reference source directory based on a specified commit.
1449
1450 Arguments:
1451 commit: commit to git-clone
1452 """
1453 self.src_dir = tempfile.mkdtemp()
Simon Glass793dca32019-10-31 07:42:57 -06001454 print("Cloning git repo to a separate work directory...")
Masahiro Yamada5cc42a52016-06-15 14:33:51 +09001455 subprocess.check_output(['git', 'clone', os.getcwd(), '.'],
1456 cwd=self.src_dir)
Simon Glass793dca32019-10-31 07:42:57 -06001457 print("Checkout '%s' to build the original autoconf.mk." % \
1458 subprocess.check_output(['git', 'rev-parse', '--short', commit]).strip())
Masahiro Yamada5cc42a52016-06-15 14:33:51 +09001459 subprocess.check_output(['git', 'checkout', commit],
1460 stderr=subprocess.STDOUT, cwd=self.src_dir)
Joe Hershberger6b96c1a2016-06-10 14:53:32 -05001461
1462 def __del__(self):
Masahiro Yamada5cc42a52016-06-15 14:33:51 +09001463 """Delete the reference source directory
Joe Hershberger6b96c1a2016-06-10 14:53:32 -05001464
1465 This function makes sure the temporary directory is cleaned away
1466 even if Python suddenly dies due to error. It should be done in here
1467 because it is guaranteed the destructor is always invoked when the
1468 instance of the class gets unreferenced.
1469 """
Masahiro Yamada5cc42a52016-06-15 14:33:51 +09001470 shutil.rmtree(self.src_dir)
Joe Hershberger6b96c1a2016-06-10 14:53:32 -05001471
Masahiro Yamada5cc42a52016-06-15 14:33:51 +09001472 def get_dir(self):
1473 """Return the absolute path to the reference source directory."""
1474
1475 return self.src_dir
Joe Hershberger6b96c1a2016-06-10 14:53:32 -05001476
Simon Glass6821a742017-07-10 14:47:47 -06001477def move_config(toolchains, configs, options, db_queue):
Masahiro Yamada5a27c732015-05-20 11:36:07 +09001478 """Move config options to defconfig files.
1479
1480 Arguments:
Masahiro Yamadab134bc12016-05-19 15:51:57 +09001481 configs: A list of CONFIGs to move.
Masahiro Yamada5a27c732015-05-20 11:36:07 +09001482 options: option flags
1483 """
Masahiro Yamadab134bc12016-05-19 15:51:57 +09001484 if len(configs) == 0:
Masahiro Yamada6a9f79f2016-05-19 15:52:09 +09001485 if options.force_sync:
Simon Glass793dca32019-10-31 07:42:57 -06001486 print('No CONFIG is specified. You are probably syncing defconfigs.', end=' ')
Simon Glassd73fcb12017-06-01 19:39:02 -06001487 elif options.build_db:
Simon Glass793dca32019-10-31 07:42:57 -06001488 print('Building %s database' % CONFIG_DATABASE)
Masahiro Yamada6a9f79f2016-05-19 15:52:09 +09001489 else:
Simon Glass793dca32019-10-31 07:42:57 -06001490 print('Neither CONFIG nor --force-sync is specified. Nothing will happen.', end=' ')
Masahiro Yamada6a9f79f2016-05-19 15:52:09 +09001491 else:
Simon Glass793dca32019-10-31 07:42:57 -06001492 print('Move ' + ', '.join(configs), end=' ')
1493 print('(jobs: %d)\n' % options.jobs)
Masahiro Yamada5a27c732015-05-20 11:36:07 +09001494
Joe Hershberger6b96c1a2016-06-10 14:53:32 -05001495 if options.git_ref:
Masahiro Yamada5cc42a52016-06-15 14:33:51 +09001496 reference_src = ReferenceSource(options.git_ref)
1497 reference_src_dir = reference_src.get_dir()
1498 else:
Masahiro Yamadaf432c332016-06-15 14:33:52 +09001499 reference_src_dir = None
Joe Hershberger6b96c1a2016-06-10 14:53:32 -05001500
Joe Hershberger91040e82015-05-19 13:21:19 -05001501 if options.defconfigs:
Masahiro Yamada0dbc9b52016-10-19 14:39:54 +09001502 defconfigs = get_matched_defconfigs(options.defconfigs)
Joe Hershberger91040e82015-05-19 13:21:19 -05001503 else:
Masahiro Yamada684c3062016-07-25 19:15:28 +09001504 defconfigs = get_all_defconfigs()
Masahiro Yamada5a27c732015-05-20 11:36:07 +09001505
Masahiro Yamadac5e60fd2016-05-19 15:51:55 +09001506 progress = Progress(len(defconfigs))
Simon Glass6821a742017-07-10 14:47:47 -06001507 slots = Slots(toolchains, configs, options, progress, reference_src_dir,
1508 db_queue)
Masahiro Yamada5a27c732015-05-20 11:36:07 +09001509
1510 # Main loop to process defconfig files:
1511 # Add a new subprocess into a vacant slot.
1512 # Sleep if there is no available slot.
Masahiro Yamadac5e60fd2016-05-19 15:51:55 +09001513 for defconfig in defconfigs:
1514 while not slots.add(defconfig):
Masahiro Yamada5a27c732015-05-20 11:36:07 +09001515 while not slots.available():
1516 # No available slot: sleep for a while
1517 time.sleep(SLEEP_TIME)
1518
1519 # wait until all the subprocesses finish
1520 while not slots.empty():
1521 time.sleep(SLEEP_TIME)
1522
Simon Glass793dca32019-10-31 07:42:57 -06001523 print('')
Masahiro Yamada5a27c732015-05-20 11:36:07 +09001524 slots.show_failed_boards()
Masahiro Yamadafc2661e2016-06-15 14:33:54 +09001525 slots.show_suspicious_boards()
Masahiro Yamada5a27c732015-05-20 11:36:07 +09001526
Simon Glasscb008832017-06-15 21:39:33 -06001527def find_kconfig_rules(kconf, config, imply_config):
1528 """Check whether a config has a 'select' or 'imply' keyword
1529
1530 Args:
Tom Rini65e05dd2019-09-20 17:42:09 -04001531 kconf: Kconfiglib.Kconfig object
Simon Glasscb008832017-06-15 21:39:33 -06001532 config: Name of config to check (without CONFIG_ prefix)
1533 imply_config: Implying config (without CONFIG_ prefix) which may or
1534 may not have an 'imply' for 'config')
1535
1536 Returns:
1537 Symbol object for 'config' if found, else None
1538 """
Tom Rini65e05dd2019-09-20 17:42:09 -04001539 sym = kconf.syms.get(imply_config)
Simon Glasscb008832017-06-15 21:39:33 -06001540 if sym:
Ulf Magnusson4e1102f2017-09-19 12:52:55 +02001541 for sel in sym.get_selected_symbols() | sym.get_implied_symbols():
Simon Glasscb008832017-06-15 21:39:33 -06001542 if sel.get_name() == config:
1543 return sym
1544 return None
1545
1546def check_imply_rule(kconf, config, imply_config):
1547 """Check if we can add an 'imply' option
1548
1549 This finds imply_config in the Kconfig and looks to see if it is possible
1550 to add an 'imply' for 'config' to that part of the Kconfig.
1551
1552 Args:
Tom Rini65e05dd2019-09-20 17:42:09 -04001553 kconf: Kconfiglib.Kconfig object
Simon Glasscb008832017-06-15 21:39:33 -06001554 config: Name of config to check (without CONFIG_ prefix)
1555 imply_config: Implying config (without CONFIG_ prefix) which may or
1556 may not have an 'imply' for 'config')
1557
1558 Returns:
1559 tuple:
1560 filename of Kconfig file containing imply_config, or None if none
1561 line number within the Kconfig file, or 0 if none
1562 message indicating the result
1563 """
Tom Rini65e05dd2019-09-20 17:42:09 -04001564 sym = kconf.syms.get(imply_config)
Simon Glasscb008832017-06-15 21:39:33 -06001565 if not sym:
1566 return 'cannot find sym'
1567 locs = sym.get_def_locations()
1568 if len(locs) != 1:
1569 return '%d locations' % len(locs)
1570 fname, linenum = locs[0]
1571 cwd = os.getcwd()
1572 if cwd and fname.startswith(cwd):
1573 fname = fname[len(cwd) + 1:]
1574 file_line = ' at %s:%d' % (fname, linenum)
1575 with open(fname) as fd:
1576 data = fd.read().splitlines()
1577 if data[linenum - 1] != 'config %s' % imply_config:
1578 return None, 0, 'bad sym format %s%s' % (data[linenum], file_line)
1579 return fname, linenum, 'adding%s' % file_line
1580
1581def add_imply_rule(config, fname, linenum):
1582 """Add a new 'imply' option to a Kconfig
1583
1584 Args:
1585 config: config option to add an imply for (without CONFIG_ prefix)
1586 fname: Kconfig filename to update
1587 linenum: Line number to place the 'imply' before
1588
1589 Returns:
1590 Message indicating the result
1591 """
1592 file_line = ' at %s:%d' % (fname, linenum)
1593 data = open(fname).read().splitlines()
1594 linenum -= 1
1595
1596 for offset, line in enumerate(data[linenum:]):
1597 if line.strip().startswith('help') or not line:
1598 data.insert(linenum + offset, '\timply %s' % config)
1599 with open(fname, 'w') as fd:
1600 fd.write('\n'.join(data) + '\n')
1601 return 'added%s' % file_line
1602
1603 return 'could not insert%s'
1604
1605(IMPLY_MIN_2, IMPLY_TARGET, IMPLY_CMD, IMPLY_NON_ARCH_BOARD) = (
1606 1, 2, 4, 8)
Simon Glass9b2a2e82017-06-15 21:39:32 -06001607
1608IMPLY_FLAGS = {
1609 'min2': [IMPLY_MIN_2, 'Show options which imply >2 boards (normally >5)'],
1610 'target': [IMPLY_TARGET, 'Allow CONFIG_TARGET_... options to imply'],
1611 'cmd': [IMPLY_CMD, 'Allow CONFIG_CMD_... to imply'],
Simon Glasscb008832017-06-15 21:39:33 -06001612 'non-arch-board': [
1613 IMPLY_NON_ARCH_BOARD,
1614 'Allow Kconfig options outside arch/ and /board/ to imply'],
Simon Glass9b2a2e82017-06-15 21:39:32 -06001615};
1616
Simon Glasscb008832017-06-15 21:39:33 -06001617def do_imply_config(config_list, add_imply, imply_flags, skip_added,
1618 check_kconfig=True, find_superset=False):
Simon Glass99b66602017-06-01 19:39:03 -06001619 """Find CONFIG options which imply those in the list
1620
1621 Some CONFIG options can be implied by others and this can help to reduce
1622 the size of the defconfig files. For example, CONFIG_X86 implies
1623 CONFIG_CMD_IRQ, so we can put 'imply CMD_IRQ' under 'config X86' and
1624 all x86 boards will have that option, avoiding adding CONFIG_CMD_IRQ to
1625 each of the x86 defconfig files.
1626
1627 This function uses the moveconfig database to find such options. It
1628 displays a list of things that could possibly imply those in the list.
1629 The algorithm ignores any that start with CONFIG_TARGET since these
1630 typically refer to only a few defconfigs (often one). It also does not
1631 display a config with less than 5 defconfigs.
1632
1633 The algorithm works using sets. For each target config in config_list:
1634 - Get the set 'defconfigs' which use that target config
1635 - For each config (from a list of all configs):
1636 - Get the set 'imply_defconfig' of defconfigs which use that config
1637 -
1638 - If imply_defconfigs contains anything not in defconfigs then
1639 this config does not imply the target config
1640
1641 Params:
1642 config_list: List of CONFIG options to check (each a string)
Simon Glasscb008832017-06-15 21:39:33 -06001643 add_imply: Automatically add an 'imply' for each config.
Simon Glass9b2a2e82017-06-15 21:39:32 -06001644 imply_flags: Flags which control which implying configs are allowed
1645 (IMPLY_...)
Simon Glasscb008832017-06-15 21:39:33 -06001646 skip_added: Don't show options which already have an imply added.
1647 check_kconfig: Check if implied symbols already have an 'imply' or
1648 'select' for the target config, and show this information if so.
Simon Glass99b66602017-06-01 19:39:03 -06001649 find_superset: True to look for configs which are a superset of those
1650 already found. So for example if CONFIG_EXYNOS5 implies an option,
1651 but CONFIG_EXYNOS covers a larger set of defconfigs and also
1652 implies that option, this will drop the former in favour of the
1653 latter. In practice this option has not proved very used.
1654
1655 Note the terminoloy:
1656 config - a CONFIG_XXX options (a string, e.g. 'CONFIG_CMD_EEPROM')
1657 defconfig - a defconfig file (a string, e.g. 'configs/snow_defconfig')
1658 """
Simon Glasscb008832017-06-15 21:39:33 -06001659 kconf = KconfigScanner().conf if check_kconfig else None
1660 if add_imply and add_imply != 'all':
1661 add_imply = add_imply.split()
1662
Simon Glass99b66602017-06-01 19:39:03 -06001663 # key is defconfig name, value is dict of (CONFIG_xxx, value)
1664 config_db = {}
1665
1666 # Holds a dict containing the set of defconfigs that contain each config
1667 # key is config, value is set of defconfigs using that config
1668 defconfig_db = collections.defaultdict(set)
1669
1670 # Set of all config options we have seen
1671 all_configs = set()
1672
1673 # Set of all defconfigs we have seen
1674 all_defconfigs = set()
1675
1676 # Read in the database
1677 configs = {}
1678 with open(CONFIG_DATABASE) as fd:
1679 for line in fd.readlines():
1680 line = line.rstrip()
1681 if not line: # Separator between defconfigs
1682 config_db[defconfig] = configs
1683 all_defconfigs.add(defconfig)
1684 configs = {}
1685 elif line[0] == ' ': # CONFIG line
1686 config, value = line.strip().split('=', 1)
1687 configs[config] = value
1688 defconfig_db[config].add(defconfig)
1689 all_configs.add(config)
1690 else: # New defconfig
1691 defconfig = line
1692
1693 # Work through each target config option in tern, independently
1694 for config in config_list:
1695 defconfigs = defconfig_db.get(config)
1696 if not defconfigs:
Simon Glass793dca32019-10-31 07:42:57 -06001697 print('%s not found in any defconfig' % config)
Simon Glass99b66602017-06-01 19:39:03 -06001698 continue
1699
1700 # Get the set of defconfigs without this one (since a config cannot
1701 # imply itself)
1702 non_defconfigs = all_defconfigs - defconfigs
1703 num_defconfigs = len(defconfigs)
Simon Glass793dca32019-10-31 07:42:57 -06001704 print('%s found in %d/%d defconfigs' % (config, num_defconfigs,
1705 len(all_configs)))
Simon Glass99b66602017-06-01 19:39:03 -06001706
1707 # This will hold the results: key=config, value=defconfigs containing it
1708 imply_configs = {}
1709 rest_configs = all_configs - set([config])
1710
1711 # Look at every possible config, except the target one
1712 for imply_config in rest_configs:
Simon Glass9b2a2e82017-06-15 21:39:32 -06001713 if 'ERRATUM' in imply_config:
Simon Glass99b66602017-06-01 19:39:03 -06001714 continue
Simon Glass9b2a2e82017-06-15 21:39:32 -06001715 if not (imply_flags & IMPLY_CMD):
1716 if 'CONFIG_CMD' in imply_config:
1717 continue
1718 if not (imply_flags & IMPLY_TARGET):
1719 if 'CONFIG_TARGET' in imply_config:
1720 continue
Simon Glass99b66602017-06-01 19:39:03 -06001721
1722 # Find set of defconfigs that have this config
1723 imply_defconfig = defconfig_db[imply_config]
1724
1725 # Get the intersection of this with defconfigs containing the
1726 # target config
1727 common_defconfigs = imply_defconfig & defconfigs
1728
1729 # Get the set of defconfigs containing this config which DO NOT
1730 # also contain the taret config. If this set is non-empty it means
1731 # that this config affects other defconfigs as well as (possibly)
1732 # the ones affected by the target config. This means it implies
1733 # things we don't want to imply.
1734 not_common_defconfigs = imply_defconfig & non_defconfigs
1735 if not_common_defconfigs:
1736 continue
1737
1738 # If there are common defconfigs, imply_config may be useful
1739 if common_defconfigs:
1740 skip = False
1741 if find_superset:
Simon Glass793dca32019-10-31 07:42:57 -06001742 for prev in list(imply_configs.keys()):
Simon Glass99b66602017-06-01 19:39:03 -06001743 prev_count = len(imply_configs[prev])
1744 count = len(common_defconfigs)
1745 if (prev_count > count and
1746 (imply_configs[prev] & common_defconfigs ==
1747 common_defconfigs)):
1748 # skip imply_config because prev is a superset
1749 skip = True
1750 break
1751 elif count > prev_count:
1752 # delete prev because imply_config is a superset
1753 del imply_configs[prev]
1754 if not skip:
1755 imply_configs[imply_config] = common_defconfigs
1756
1757 # Now we have a dict imply_configs of configs which imply each config
1758 # The value of each dict item is the set of defconfigs containing that
1759 # config. Rank them so that we print the configs that imply the largest
1760 # number of defconfigs first.
Simon Glasscb008832017-06-15 21:39:33 -06001761 ranked_iconfigs = sorted(imply_configs,
Simon Glass99b66602017-06-01 19:39:03 -06001762 key=lambda k: len(imply_configs[k]), reverse=True)
Simon Glasscb008832017-06-15 21:39:33 -06001763 kconfig_info = ''
1764 cwd = os.getcwd()
1765 add_list = collections.defaultdict(list)
1766 for iconfig in ranked_iconfigs:
1767 num_common = len(imply_configs[iconfig])
Simon Glass99b66602017-06-01 19:39:03 -06001768
1769 # Don't bother if there are less than 5 defconfigs affected.
Simon Glass9b2a2e82017-06-15 21:39:32 -06001770 if num_common < (2 if imply_flags & IMPLY_MIN_2 else 5):
Simon Glass99b66602017-06-01 19:39:03 -06001771 continue
Simon Glasscb008832017-06-15 21:39:33 -06001772 missing = defconfigs - imply_configs[iconfig]
Simon Glass99b66602017-06-01 19:39:03 -06001773 missing_str = ', '.join(missing) if missing else 'all'
1774 missing_str = ''
Simon Glasscb008832017-06-15 21:39:33 -06001775 show = True
1776 if kconf:
1777 sym = find_kconfig_rules(kconf, config[CONFIG_LEN:],
1778 iconfig[CONFIG_LEN:])
1779 kconfig_info = ''
1780 if sym:
1781 locs = sym.get_def_locations()
1782 if len(locs) == 1:
1783 fname, linenum = locs[0]
1784 if cwd and fname.startswith(cwd):
1785 fname = fname[len(cwd) + 1:]
1786 kconfig_info = '%s:%d' % (fname, linenum)
1787 if skip_added:
1788 show = False
1789 else:
Tom Rini65e05dd2019-09-20 17:42:09 -04001790 sym = kconf.syms.get(iconfig[CONFIG_LEN:])
Simon Glasscb008832017-06-15 21:39:33 -06001791 fname = ''
1792 if sym:
1793 locs = sym.get_def_locations()
1794 if len(locs) == 1:
1795 fname, linenum = locs[0]
1796 if cwd and fname.startswith(cwd):
1797 fname = fname[len(cwd) + 1:]
1798 in_arch_board = not sym or (fname.startswith('arch') or
1799 fname.startswith('board'))
1800 if (not in_arch_board and
1801 not (imply_flags & IMPLY_NON_ARCH_BOARD)):
1802 continue
1803
1804 if add_imply and (add_imply == 'all' or
1805 iconfig in add_imply):
1806 fname, linenum, kconfig_info = (check_imply_rule(kconf,
1807 config[CONFIG_LEN:], iconfig[CONFIG_LEN:]))
1808 if fname:
1809 add_list[fname].append(linenum)
1810
1811 if show and kconfig_info != 'skip':
Simon Glass793dca32019-10-31 07:42:57 -06001812 print('%5d : %-30s%-25s %s' % (num_common, iconfig.ljust(30),
1813 kconfig_info, missing_str))
Simon Glasscb008832017-06-15 21:39:33 -06001814
1815 # Having collected a list of things to add, now we add them. We process
1816 # each file from the largest line number to the smallest so that
1817 # earlier additions do not affect our line numbers. E.g. if we added an
1818 # imply at line 20 it would change the position of each line after
1819 # that.
Simon Glass793dca32019-10-31 07:42:57 -06001820 for fname, linenums in add_list.items():
Simon Glasscb008832017-06-15 21:39:33 -06001821 for linenum in sorted(linenums, reverse=True):
1822 add_imply_rule(config[CONFIG_LEN:], fname, linenum)
Simon Glass99b66602017-06-01 19:39:03 -06001823
1824
Masahiro Yamada5a27c732015-05-20 11:36:07 +09001825def main():
1826 try:
1827 cpu_count = multiprocessing.cpu_count()
1828 except NotImplementedError:
1829 cpu_count = 1
1830
1831 parser = optparse.OptionParser()
1832 # Add options here
Simon Glasscb008832017-06-15 21:39:33 -06001833 parser.add_option('-a', '--add-imply', type='string', default='',
1834 help='comma-separated list of CONFIG options to add '
1835 "an 'imply' statement to for the CONFIG in -i")
1836 parser.add_option('-A', '--skip-added', action='store_true', default=False,
1837 help="don't show options which are already marked as "
1838 'implying others')
Simon Glassd73fcb12017-06-01 19:39:02 -06001839 parser.add_option('-b', '--build-db', action='store_true', default=False,
1840 help='build a CONFIG database')
Masahiro Yamada5a27c732015-05-20 11:36:07 +09001841 parser.add_option('-c', '--color', action='store_true', default=False,
1842 help='display the log in color')
Simon Glass9ede2122016-09-12 23:18:21 -06001843 parser.add_option('-C', '--commit', action='store_true', default=False,
1844 help='Create a git commit for the operation')
Joe Hershberger91040e82015-05-19 13:21:19 -05001845 parser.add_option('-d', '--defconfigs', type='string',
Simon Glassee4e61b2017-06-01 19:38:59 -06001846 help='a file containing a list of defconfigs to move, '
1847 "one per line (for example 'snow_defconfig') "
1848 "or '-' to read from stdin")
Simon Glass99b66602017-06-01 19:39:03 -06001849 parser.add_option('-i', '--imply', action='store_true', default=False,
1850 help='find options which imply others')
Simon Glass9b2a2e82017-06-15 21:39:32 -06001851 parser.add_option('-I', '--imply-flags', type='string', default='',
1852 help="control the -i option ('help' for help")
Masahiro Yamada5a27c732015-05-20 11:36:07 +09001853 parser.add_option('-n', '--dry-run', action='store_true', default=False,
1854 help='perform a trial run (show log with no changes)')
1855 parser.add_option('-e', '--exit-on-error', action='store_true',
1856 default=False,
1857 help='exit immediately on any error')
Masahiro Yamada8513dc02016-05-19 15:52:08 +09001858 parser.add_option('-s', '--force-sync', action='store_true', default=False,
1859 help='force sync by savedefconfig')
Masahiro Yamada07913d12016-08-22 22:18:22 +09001860 parser.add_option('-S', '--spl', action='store_true', default=False,
1861 help='parse config options defined for SPL build')
Joe Hershberger2144f882015-05-19 13:21:20 -05001862 parser.add_option('-H', '--headers-only', dest='cleanup_headers_only',
1863 action='store_true', default=False,
1864 help='only cleanup the headers')
Masahiro Yamada5a27c732015-05-20 11:36:07 +09001865 parser.add_option('-j', '--jobs', type='int', default=cpu_count,
1866 help='the number of jobs to run simultaneously')
Joe Hershberger6b96c1a2016-06-10 14:53:32 -05001867 parser.add_option('-r', '--git-ref', type='string',
1868 help='the git ref to clone for building the autoconf.mk')
Simon Glass6b403df2016-09-12 23:18:20 -06001869 parser.add_option('-y', '--yes', action='store_true', default=False,
1870 help="respond 'yes' to any prompts")
Joe Hershberger95bf9c72015-05-19 13:21:24 -05001871 parser.add_option('-v', '--verbose', action='store_true', default=False,
1872 help='show any build errors as boards are built')
Masahiro Yamadab6ef3932016-05-19 15:51:58 +09001873 parser.usage += ' CONFIG ...'
Masahiro Yamada5a27c732015-05-20 11:36:07 +09001874
Masahiro Yamadab6ef3932016-05-19 15:51:58 +09001875 (options, configs) = parser.parse_args()
Masahiro Yamada5a27c732015-05-20 11:36:07 +09001876
Simon Glass99b66602017-06-01 19:39:03 -06001877 if len(configs) == 0 and not any((options.force_sync, options.build_db,
1878 options.imply)):
Masahiro Yamada5a27c732015-05-20 11:36:07 +09001879 parser.print_usage()
1880 sys.exit(1)
1881
Masahiro Yamadab6ef3932016-05-19 15:51:58 +09001882 # prefix the option name with CONFIG_ if missing
1883 configs = [ config if config.startswith('CONFIG_') else 'CONFIG_' + config
1884 for config in configs ]
Masahiro Yamada5a27c732015-05-20 11:36:07 +09001885
Joe Hershberger2144f882015-05-19 13:21:20 -05001886 check_top_directory()
1887
Simon Glass99b66602017-06-01 19:39:03 -06001888 if options.imply:
Simon Glass9b2a2e82017-06-15 21:39:32 -06001889 imply_flags = 0
Simon Glassdee36c72017-07-10 14:47:46 -06001890 if options.imply_flags == 'all':
1891 imply_flags = -1
1892
1893 elif options.imply_flags:
1894 for flag in options.imply_flags.split(','):
1895 bad = flag not in IMPLY_FLAGS
1896 if bad:
Simon Glass793dca32019-10-31 07:42:57 -06001897 print("Invalid flag '%s'" % flag)
Simon Glassdee36c72017-07-10 14:47:46 -06001898 if flag == 'help' or bad:
Simon Glass793dca32019-10-31 07:42:57 -06001899 print("Imply flags: (separate with ',')")
1900 for name, info in IMPLY_FLAGS.items():
1901 print(' %-15s: %s' % (name, info[1]))
Simon Glassdee36c72017-07-10 14:47:46 -06001902 parser.print_usage()
1903 sys.exit(1)
1904 imply_flags |= IMPLY_FLAGS[flag][0]
Simon Glass9b2a2e82017-06-15 21:39:32 -06001905
Simon Glasscb008832017-06-15 21:39:33 -06001906 do_imply_config(configs, options.add_imply, imply_flags,
1907 options.skip_added)
Simon Glass99b66602017-06-01 19:39:03 -06001908 return
1909
Simon Glassd73fcb12017-06-01 19:39:02 -06001910 config_db = {}
Simon Glass793dca32019-10-31 07:42:57 -06001911 db_queue = queue.Queue()
Simon Glassd73fcb12017-06-01 19:39:02 -06001912 t = DatabaseThread(config_db, db_queue)
1913 t.setDaemon(True)
1914 t.start()
1915
Joe Hershberger2144f882015-05-19 13:21:20 -05001916 if not options.cleanup_headers_only:
Masahiro Yamadaf7536f72016-07-25 19:15:23 +09001917 check_clean_directory()
Simon Glass793dca32019-10-31 07:42:57 -06001918 bsettings.Setup('')
Simon Glass6821a742017-07-10 14:47:47 -06001919 toolchains = toolchain.Toolchains()
1920 toolchains.GetSettings()
1921 toolchains.Scan(verbose=False)
1922 move_config(toolchains, configs, options, db_queue)
Simon Glassd73fcb12017-06-01 19:39:02 -06001923 db_queue.join()
Joe Hershberger2144f882015-05-19 13:21:20 -05001924
Masahiro Yamada6a9f79f2016-05-19 15:52:09 +09001925 if configs:
Masahiro Yamadae9ea1222016-07-25 19:15:26 +09001926 cleanup_headers(configs, options)
Masahiro Yamada9ab02962016-07-25 19:15:29 +09001927 cleanup_extra_options(configs, options)
Chris Packhamca438342017-05-02 21:30:47 +12001928 cleanup_whitelist(configs, options)
Chris Packhamf90df592017-05-02 21:30:48 +12001929 cleanup_readme(configs, options)
Masahiro Yamada5a27c732015-05-20 11:36:07 +09001930
Simon Glass9ede2122016-09-12 23:18:21 -06001931 if options.commit:
1932 subprocess.call(['git', 'add', '-u'])
1933 if configs:
1934 msg = 'Convert %s %sto Kconfig' % (configs[0],
1935 'et al ' if len(configs) > 1 else '')
1936 msg += ('\n\nThis converts the following to Kconfig:\n %s\n' %
1937 '\n '.join(configs))
1938 else:
1939 msg = 'configs: Resync with savedefconfig'
1940 msg += '\n\nRsync all defconfig files using moveconfig.py'
1941 subprocess.call(['git', 'commit', '-s', '-m', msg])
1942
Simon Glassd73fcb12017-06-01 19:39:02 -06001943 if options.build_db:
1944 with open(CONFIG_DATABASE, 'w') as fd:
Simon Glass793dca32019-10-31 07:42:57 -06001945 for defconfig, configs in config_db.items():
Simon Glassc79d18c2017-08-13 16:02:54 -06001946 fd.write('%s\n' % defconfig)
Simon Glassd73fcb12017-06-01 19:39:02 -06001947 for config in sorted(configs.keys()):
Simon Glassc79d18c2017-08-13 16:02:54 -06001948 fd.write(' %s=%s\n' % (config, configs[config]))
1949 fd.write('\n')
Simon Glassd73fcb12017-06-01 19:39:02 -06001950
Masahiro Yamada5a27c732015-05-20 11:36:07 +09001951if __name__ == '__main__':
1952 main()