moveconfig.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878
  1. #!/usr/bin/env python2
  2. #
  3. # Author: Masahiro Yamada <yamada.masahiro@socionext.com>
  4. #
  5. # SPDX-License-Identifier: GPL-2.0+
  6. #
  7. """
  8. Move config options from headers to defconfig files.
  9. Since Kconfig was introduced to U-Boot, we have worked on moving
  10. config options from headers to Kconfig (defconfig).
  11. This tool intends to help this tremendous work.
  12. Usage
  13. -----
  14. First, you must edit the Kconfig to add the menu entries for the configs
  15. you are moving.
  16. And then run this tool giving CONFIG names you want to move.
  17. For example, if you want to move CONFIG_CMD_USB and CONFIG_SYS_TEXT_BASE,
  18. simply type as follows:
  19. $ tools/moveconfig.py CONFIG_CMD_USB CONFIG_SYS_TEXT_BASE
  20. The tool walks through all the defconfig files and move the given CONFIGs.
  21. The log is also displayed on the terminal.
  22. The log is printed for each defconfig as follows:
  23. <defconfig_name>
  24. <action1>
  25. <action2>
  26. <action3>
  27. ...
  28. <defconfig_name> is the name of the defconfig.
  29. <action*> shows what the tool did for that defconfig.
  30. It looks like one of the followings:
  31. - Move 'CONFIG_... '
  32. This config option was moved to the defconfig
  33. - CONFIG_... is not defined in Kconfig. Do nothing.
  34. The entry for this CONFIG was not found in Kconfig.
  35. There are two common cases:
  36. - You forgot to create an entry for the CONFIG before running
  37. this tool, or made a typo in a CONFIG passed to this tool.
  38. - The entry was hidden due to unmet 'depends on'.
  39. This is correct behavior.
  40. - 'CONFIG_...' is the same as the define in Kconfig. Do nothing.
  41. The define in the config header matched the one in Kconfig.
  42. We do not need to touch it.
  43. - Undefined. Do nothing.
  44. This config option was not found in the config header.
  45. Nothing to do.
  46. - Compiler is missing. Do nothing.
  47. The compiler specified for this architecture was not found
  48. in your PATH environment.
  49. (If -e option is passed, the tool exits immediately.)
  50. - Failed to process.
  51. An error occurred during processing this defconfig. Skipped.
  52. (If -e option is passed, the tool exits immediately on error.)
  53. Finally, you will be asked, Clean up headers? [y/n]:
  54. If you say 'y' here, the unnecessary config defines are removed
  55. from the config headers (include/configs/*.h).
  56. It just uses the regex method, so you should not rely on it.
  57. Just in case, please do 'git diff' to see what happened.
  58. How does it work?
  59. -----------------
  60. This tool runs configuration and builds include/autoconf.mk for every
  61. defconfig. The config options defined in Kconfig appear in the .config
  62. file (unless they are hidden because of unmet dependency.)
  63. On the other hand, the config options defined by board headers are seen
  64. in include/autoconf.mk. The tool looks for the specified options in both
  65. of them to decide the appropriate action for the options. If the given
  66. config option is found in the .config, but its value does not match the
  67. one from the board header, the config option in the .config is replaced
  68. with the define in the board header. Then, the .config is synced by
  69. "make savedefconfig" and the defconfig is updated with it.
  70. For faster processing, this tool handles multi-threading. It creates
  71. separate build directories where the out-of-tree build is run. The
  72. temporary build directories are automatically created and deleted as
  73. needed. The number of threads are chosen based on the number of the CPU
  74. cores of your system although you can change it via -j (--jobs) option.
  75. Toolchains
  76. ----------
  77. Appropriate toolchain are necessary to generate include/autoconf.mk
  78. for all the architectures supported by U-Boot. Most of them are available
  79. at the kernel.org site, some are not provided by kernel.org.
  80. The default per-arch CROSS_COMPILE used by this tool is specified by
  81. the list below, CROSS_COMPILE. You may wish to update the list to
  82. use your own. Instead of modifying the list directly, you can give
  83. them via environments.
  84. Available options
  85. -----------------
  86. -c, --color
  87. Surround each portion of the log with escape sequences to display it
  88. in color on the terminal.
  89. -d, --defconfigs
  90. Specify a file containing a list of defconfigs to move
  91. -n, --dry-run
  92. Perform a trial run that does not make any changes. It is useful to
  93. see what is going to happen before one actually runs it.
  94. -e, --exit-on-error
  95. Exit immediately if Make exits with a non-zero status while processing
  96. a defconfig file.
  97. -H, --headers-only
  98. Only cleanup the headers; skip the defconfig processing
  99. -j, --jobs
  100. Specify the number of threads to run simultaneously. If not specified,
  101. the number of threads is the same as the number of CPU cores.
  102. -v, --verbose
  103. Show any build errors as boards are built
  104. To see the complete list of supported options, run
  105. $ tools/moveconfig.py -h
  106. """
  107. import fnmatch
  108. import multiprocessing
  109. import optparse
  110. import os
  111. import re
  112. import shutil
  113. import subprocess
  114. import sys
  115. import tempfile
  116. import time
  117. SHOW_GNU_MAKE = 'scripts/show-gnu-make'
  118. SLEEP_TIME=0.03
  119. # Here is the list of cross-tools I use.
  120. # Most of them are available at kernel.org
  121. # (https://www.kernel.org/pub/tools/crosstool/files/bin/), except the followings:
  122. # arc: https://github.com/foss-for-synopsys-dwc-arc-processors/toolchain/releases
  123. # blackfin: http://sourceforge.net/projects/adi-toolchain/files/
  124. # nds32: http://osdk.andestech.com/packages/nds32le-linux-glibc-v1.tgz
  125. # nios2: https://sourcery.mentor.com/GNUToolchain/subscription42545
  126. # sh: http://sourcery.mentor.com/public/gnu_toolchain/sh-linux-gnu
  127. #
  128. # openrisc kernel.org toolchain is out of date, download latest one from
  129. # http://opencores.org/or1k/OpenRISC_GNU_tool_chain#Prebuilt_versions
  130. CROSS_COMPILE = {
  131. 'arc': 'arc-linux-',
  132. 'aarch64': 'aarch64-linux-',
  133. 'arm': 'arm-unknown-linux-gnueabi-',
  134. 'avr32': 'avr32-linux-',
  135. 'blackfin': 'bfin-elf-',
  136. 'm68k': 'm68k-linux-',
  137. 'microblaze': 'microblaze-linux-',
  138. 'mips': 'mips-linux-',
  139. 'nds32': 'nds32le-linux-',
  140. 'nios2': 'nios2-linux-gnu-',
  141. 'openrisc': 'or1k-elf-',
  142. 'powerpc': 'powerpc-linux-',
  143. 'sh': 'sh-linux-gnu-',
  144. 'sparc': 'sparc-linux-',
  145. 'x86': 'i386-linux-'
  146. }
  147. STATE_IDLE = 0
  148. STATE_DEFCONFIG = 1
  149. STATE_AUTOCONF = 2
  150. STATE_SAVEDEFCONFIG = 3
  151. ACTION_MOVE = 0
  152. ACTION_NO_ENTRY = 1
  153. ACTION_NO_CHANGE = 2
  154. COLOR_BLACK = '0;30'
  155. COLOR_RED = '0;31'
  156. COLOR_GREEN = '0;32'
  157. COLOR_BROWN = '0;33'
  158. COLOR_BLUE = '0;34'
  159. COLOR_PURPLE = '0;35'
  160. COLOR_CYAN = '0;36'
  161. COLOR_LIGHT_GRAY = '0;37'
  162. COLOR_DARK_GRAY = '1;30'
  163. COLOR_LIGHT_RED = '1;31'
  164. COLOR_LIGHT_GREEN = '1;32'
  165. COLOR_YELLOW = '1;33'
  166. COLOR_LIGHT_BLUE = '1;34'
  167. COLOR_LIGHT_PURPLE = '1;35'
  168. COLOR_LIGHT_CYAN = '1;36'
  169. COLOR_WHITE = '1;37'
  170. ### helper functions ###
  171. def get_devnull():
  172. """Get the file object of '/dev/null' device."""
  173. try:
  174. devnull = subprocess.DEVNULL # py3k
  175. except AttributeError:
  176. devnull = open(os.devnull, 'wb')
  177. return devnull
  178. def check_top_directory():
  179. """Exit if we are not at the top of source directory."""
  180. for f in ('README', 'Licenses'):
  181. if not os.path.exists(f):
  182. sys.exit('Please run at the top of source directory.')
  183. def check_clean_directory():
  184. """Exit if the source tree is not clean."""
  185. for f in ('.config', 'include/config'):
  186. if os.path.exists(f):
  187. sys.exit("source tree is not clean, please run 'make mrproper'")
  188. def get_make_cmd():
  189. """Get the command name of GNU Make.
  190. U-Boot needs GNU Make for building, but the command name is not
  191. necessarily "make". (for example, "gmake" on FreeBSD).
  192. Returns the most appropriate command name on your system.
  193. """
  194. process = subprocess.Popen([SHOW_GNU_MAKE], stdout=subprocess.PIPE)
  195. ret = process.communicate()
  196. if process.returncode:
  197. sys.exit('GNU Make not found')
  198. return ret[0].rstrip()
  199. def color_text(color_enabled, color, string):
  200. """Return colored string."""
  201. if color_enabled:
  202. # LF should not be surrounded by the escape sequence.
  203. # Otherwise, additional whitespace or line-feed might be printed.
  204. return '\n'.join([ '\033[' + color + 'm' + s + '\033[0m' if s else ''
  205. for s in string.split('\n') ])
  206. else:
  207. return string
  208. def update_cross_compile(color_enabled):
  209. """Update per-arch CROSS_COMPILE via environment variables
  210. The default CROSS_COMPILE values are available
  211. in the CROSS_COMPILE list above.
  212. You can override them via environment variables
  213. CROSS_COMPILE_{ARCH}.
  214. For example, if you want to override toolchain prefixes
  215. for ARM and PowerPC, you can do as follows in your shell:
  216. export CROSS_COMPILE_ARM=...
  217. export CROSS_COMPILE_POWERPC=...
  218. Then, this function checks if specified compilers really exist in your
  219. PATH environment.
  220. """
  221. archs = []
  222. for arch in os.listdir('arch'):
  223. if os.path.exists(os.path.join('arch', arch, 'Makefile')):
  224. archs.append(arch)
  225. # arm64 is a special case
  226. archs.append('aarch64')
  227. for arch in archs:
  228. env = 'CROSS_COMPILE_' + arch.upper()
  229. cross_compile = os.environ.get(env)
  230. if not cross_compile:
  231. cross_compile = CROSS_COMPILE.get(arch, '')
  232. for path in os.environ["PATH"].split(os.pathsep):
  233. gcc_path = os.path.join(path, cross_compile + 'gcc')
  234. if os.path.isfile(gcc_path) and os.access(gcc_path, os.X_OK):
  235. break
  236. else:
  237. print >> sys.stderr, color_text(color_enabled, COLOR_YELLOW,
  238. 'warning: %sgcc: not found in PATH. %s architecture boards will be skipped'
  239. % (cross_compile, arch))
  240. cross_compile = None
  241. CROSS_COMPILE[arch] = cross_compile
  242. def cleanup_one_header(header_path, patterns, dry_run):
  243. """Clean regex-matched lines away from a file.
  244. Arguments:
  245. header_path: path to the cleaned file.
  246. patterns: list of regex patterns. Any lines matching to these
  247. patterns are deleted.
  248. dry_run: make no changes, but still display log.
  249. """
  250. with open(header_path) as f:
  251. lines = f.readlines()
  252. matched = []
  253. for i, line in enumerate(lines):
  254. for pattern in patterns:
  255. m = pattern.search(line)
  256. if m:
  257. print '%s: %s: %s' % (header_path, i + 1, line),
  258. matched.append(i)
  259. break
  260. if dry_run or not matched:
  261. return
  262. with open(header_path, 'w') as f:
  263. for i, line in enumerate(lines):
  264. if not i in matched:
  265. f.write(line)
  266. def cleanup_headers(configs, dry_run):
  267. """Delete config defines from board headers.
  268. Arguments:
  269. configs: A list of CONFIGs to remove.
  270. dry_run: make no changes, but still display log.
  271. """
  272. while True:
  273. choice = raw_input('Clean up headers? [y/n]: ').lower()
  274. print choice
  275. if choice == 'y' or choice == 'n':
  276. break
  277. if choice == 'n':
  278. return
  279. patterns = []
  280. for config in configs:
  281. patterns.append(re.compile(r'#\s*define\s+%s\W' % config))
  282. patterns.append(re.compile(r'#\s*undef\s+%s\W' % config))
  283. for dir in 'include', 'arch', 'board':
  284. for (dirpath, dirnames, filenames) in os.walk(dir):
  285. for filename in filenames:
  286. if not fnmatch.fnmatch(filename, '*~'):
  287. cleanup_one_header(os.path.join(dirpath, filename),
  288. patterns, dry_run)
  289. ### classes ###
  290. class Progress:
  291. """Progress Indicator"""
  292. def __init__(self, total):
  293. """Create a new progress indicator.
  294. Arguments:
  295. total: A number of defconfig files to process.
  296. """
  297. self.current = 0
  298. self.total = total
  299. def inc(self):
  300. """Increment the number of processed defconfig files."""
  301. self.current += 1
  302. def show(self):
  303. """Display the progress."""
  304. print ' %d defconfigs out of %d\r' % (self.current, self.total),
  305. sys.stdout.flush()
  306. class KconfigParser:
  307. """A parser of .config and include/autoconf.mk."""
  308. re_arch = re.compile(r'CONFIG_SYS_ARCH="(.*)"')
  309. re_cpu = re.compile(r'CONFIG_SYS_CPU="(.*)"')
  310. def __init__(self, configs, options, build_dir):
  311. """Create a new parser.
  312. Arguments:
  313. configs: A list of CONFIGs to move.
  314. options: option flags.
  315. build_dir: Build directory.
  316. """
  317. self.configs = configs
  318. self.options = options
  319. self.dotconfig = os.path.join(build_dir, '.config')
  320. self.autoconf = os.path.join(build_dir, 'include', 'autoconf.mk')
  321. self.config_autoconf = os.path.join(build_dir, 'include', 'config',
  322. 'auto.conf')
  323. def get_cross_compile(self):
  324. """Parse .config file and return CROSS_COMPILE.
  325. Returns:
  326. A string storing the compiler prefix for the architecture.
  327. Return a NULL string for architectures that do not require
  328. compiler prefix (Sandbox and native build is the case).
  329. Return None if the specified compiler is missing in your PATH.
  330. Caller should distinguish '' and None.
  331. """
  332. arch = ''
  333. cpu = ''
  334. for line in open(self.dotconfig):
  335. m = self.re_arch.match(line)
  336. if m:
  337. arch = m.group(1)
  338. continue
  339. m = self.re_cpu.match(line)
  340. if m:
  341. cpu = m.group(1)
  342. if not arch:
  343. return None
  344. # fix-up for aarch64
  345. if arch == 'arm' and cpu == 'armv8':
  346. arch = 'aarch64'
  347. return CROSS_COMPILE.get(arch, None)
  348. def parse_one_config(self, config, dotconfig_lines, autoconf_lines):
  349. """Parse .config, defconfig, include/autoconf.mk for one config.
  350. This function looks for the config options in the lines from
  351. defconfig, .config, and include/autoconf.mk in order to decide
  352. which action should be taken for this defconfig.
  353. Arguments:
  354. config: CONFIG name to parse.
  355. dotconfig_lines: lines from the .config file.
  356. autoconf_lines: lines from the include/autoconf.mk file.
  357. Returns:
  358. A tupple of the action for this defconfig and the line
  359. matched for the config.
  360. """
  361. not_set = '# %s is not set' % config
  362. for line in dotconfig_lines:
  363. line = line.rstrip()
  364. if line.startswith(config + '=') or line == not_set:
  365. old_val = line
  366. break
  367. else:
  368. return (ACTION_NO_ENTRY, config)
  369. for line in autoconf_lines:
  370. line = line.rstrip()
  371. if line.startswith(config + '='):
  372. new_val = line
  373. break
  374. else:
  375. new_val = not_set
  376. if old_val == new_val:
  377. return (ACTION_NO_CHANGE, new_val)
  378. # If this CONFIG is neither bool nor trisate
  379. if old_val[-2:] != '=y' and old_val[-2:] != '=m' and old_val != not_set:
  380. # tools/scripts/define2mk.sed changes '1' to 'y'.
  381. # This is a problem if the CONFIG is int type.
  382. # Check the type in Kconfig and handle it correctly.
  383. if new_val[-2:] == '=y':
  384. new_val = new_val[:-1] + '1'
  385. return (ACTION_MOVE, new_val)
  386. def update_dotconfig(self):
  387. """Parse files for the config options and update the .config.
  388. This function parses the generated .config and include/autoconf.mk
  389. searching the target options.
  390. Move the config option(s) to the .config as needed.
  391. Arguments:
  392. defconfig: defconfig name.
  393. Returns:
  394. Return log string
  395. """
  396. results = []
  397. with open(self.dotconfig) as f:
  398. dotconfig_lines = f.readlines()
  399. with open(self.autoconf) as f:
  400. autoconf_lines = f.readlines()
  401. for config in self.configs:
  402. result = self.parse_one_config(config, dotconfig_lines,
  403. autoconf_lines)
  404. results.append(result)
  405. log = ''
  406. for (action, value) in results:
  407. if action == ACTION_MOVE:
  408. actlog = "Move '%s'" % value
  409. log_color = COLOR_LIGHT_GREEN
  410. elif action == ACTION_NO_ENTRY:
  411. actlog = "%s is not defined in Kconfig. Do nothing." % value
  412. log_color = COLOR_LIGHT_BLUE
  413. elif action == ACTION_NO_CHANGE:
  414. actlog = "'%s' is the same as the define in Kconfig. Do nothing." \
  415. % value
  416. log_color = COLOR_LIGHT_PURPLE
  417. else:
  418. sys.exit("Internal Error. This should not happen.")
  419. log += color_text(self.options.color, log_color, actlog) + '\n'
  420. with open(self.dotconfig, 'a') as f:
  421. for (action, value) in results:
  422. if action == ACTION_MOVE:
  423. f.write(value + '\n')
  424. os.remove(self.config_autoconf)
  425. os.remove(self.autoconf)
  426. return log
  427. class Slot:
  428. """A slot to store a subprocess.
  429. Each instance of this class handles one subprocess.
  430. This class is useful to control multiple threads
  431. for faster processing.
  432. """
  433. def __init__(self, configs, options, progress, devnull, make_cmd):
  434. """Create a new process slot.
  435. Arguments:
  436. configs: A list of CONFIGs to move.
  437. options: option flags.
  438. progress: A progress indicator.
  439. devnull: A file object of '/dev/null'.
  440. make_cmd: command name of GNU Make.
  441. """
  442. self.options = options
  443. self.progress = progress
  444. self.build_dir = tempfile.mkdtemp()
  445. self.devnull = devnull
  446. self.make_cmd = (make_cmd, 'O=' + self.build_dir)
  447. self.parser = KconfigParser(configs, options, self.build_dir)
  448. self.state = STATE_IDLE
  449. self.failed_boards = []
  450. def __del__(self):
  451. """Delete the working directory
  452. This function makes sure the temporary directory is cleaned away
  453. even if Python suddenly dies due to error. It should be done in here
  454. because it is guranteed the destructor is always invoked when the
  455. instance of the class gets unreferenced.
  456. If the subprocess is still running, wait until it finishes.
  457. """
  458. if self.state != STATE_IDLE:
  459. while self.ps.poll() == None:
  460. pass
  461. shutil.rmtree(self.build_dir)
  462. def add(self, defconfig):
  463. """Assign a new subprocess for defconfig and add it to the slot.
  464. If the slot is vacant, create a new subprocess for processing the
  465. given defconfig and add it to the slot. Just returns False if
  466. the slot is occupied (i.e. the current subprocess is still running).
  467. Arguments:
  468. defconfig: defconfig name.
  469. Returns:
  470. Return True on success or False on failure
  471. """
  472. if self.state != STATE_IDLE:
  473. return False
  474. cmd = list(self.make_cmd)
  475. cmd.append(defconfig)
  476. self.ps = subprocess.Popen(cmd, stdout=self.devnull,
  477. stderr=subprocess.PIPE)
  478. self.defconfig = defconfig
  479. self.state = STATE_DEFCONFIG
  480. self.log = ''
  481. return True
  482. def poll(self):
  483. """Check the status of the subprocess and handle it as needed.
  484. Returns True if the slot is vacant (i.e. in idle state).
  485. If the configuration is successfully finished, assign a new
  486. subprocess to build include/autoconf.mk.
  487. If include/autoconf.mk is generated, invoke the parser to
  488. parse the .config and the include/autoconf.mk, and then set the
  489. slot back to the idle state.
  490. Returns:
  491. Return True if the subprocess is terminated, False otherwise
  492. """
  493. if self.state == STATE_IDLE:
  494. return True
  495. if self.ps.poll() == None:
  496. return False
  497. if self.ps.poll() != 0:
  498. self.log += color_text(self.options.color, COLOR_LIGHT_RED,
  499. "Failed to process.\n")
  500. if self.options.verbose:
  501. self.log += color_text(self.options.color, COLOR_LIGHT_CYAN,
  502. self.ps.stderr.read())
  503. self.show_log(sys.stderr)
  504. if self.options.exit_on_error:
  505. sys.exit("Exit on error.")
  506. # If --exit-on-error flag is not set, skip this board and continue.
  507. # Record the failed board.
  508. self.failed_boards.append(self.defconfig)
  509. self.state = STATE_IDLE
  510. return True
  511. if self.state == STATE_AUTOCONF:
  512. self.log += self.parser.update_dotconfig()
  513. """Save off the defconfig in a consistent way"""
  514. cmd = list(self.make_cmd)
  515. cmd.append('savedefconfig')
  516. self.ps = subprocess.Popen(cmd, stdout=self.devnull,
  517. stderr=subprocess.PIPE)
  518. self.state = STATE_SAVEDEFCONFIG
  519. return False
  520. if self.state == STATE_SAVEDEFCONFIG:
  521. if not self.options.dry_run:
  522. shutil.move(os.path.join(self.build_dir, 'defconfig'),
  523. os.path.join('configs', self.defconfig))
  524. self.show_log()
  525. self.state = STATE_IDLE
  526. return True
  527. self.cross_compile = self.parser.get_cross_compile()
  528. if self.cross_compile is None:
  529. self.log += color_text(self.options.color, COLOR_YELLOW,
  530. "Compiler is missing. Do nothing.\n")
  531. self.show_log(sys.stderr)
  532. if self.options.exit_on_error:
  533. sys.exit("Exit on error.")
  534. # If --exit-on-error flag is not set, skip this board and continue.
  535. # Record the failed board.
  536. self.failed_boards.append(self.defconfig)
  537. self.state = STATE_IDLE
  538. return True
  539. cmd = list(self.make_cmd)
  540. if self.cross_compile:
  541. cmd.append('CROSS_COMPILE=%s' % self.cross_compile)
  542. cmd.append('KCONFIG_IGNORE_DUPLICATES=1')
  543. cmd.append('include/config/auto.conf')
  544. self.ps = subprocess.Popen(cmd, stdout=self.devnull,
  545. stderr=subprocess.PIPE)
  546. self.state = STATE_AUTOCONF
  547. return False
  548. def show_log(self, file=sys.stdout):
  549. """Display log along with progress.
  550. Arguments:
  551. file: A file object to which the log string is sent.
  552. """
  553. # output at least 30 characters to hide the "* defconfigs out of *".
  554. log = self.defconfig.ljust(30) + '\n'
  555. log += '\n'.join([ ' ' + s for s in self.log.split('\n') ])
  556. # Some threads are running in parallel.
  557. # Print log atomically to not mix up logs from different threads.
  558. print >> file, log
  559. self.progress.inc()
  560. self.progress.show()
  561. def get_failed_boards(self):
  562. """Returns a list of failed boards (defconfigs) in this slot.
  563. """
  564. return self.failed_boards
  565. class Slots:
  566. """Controller of the array of subprocess slots."""
  567. def __init__(self, configs, options, progress):
  568. """Create a new slots controller.
  569. Arguments:
  570. configs: A list of CONFIGs to move.
  571. options: option flags.
  572. progress: A progress indicator.
  573. """
  574. self.options = options
  575. self.slots = []
  576. devnull = get_devnull()
  577. make_cmd = get_make_cmd()
  578. for i in range(options.jobs):
  579. self.slots.append(Slot(configs, options, progress, devnull,
  580. make_cmd))
  581. def add(self, defconfig):
  582. """Add a new subprocess if a vacant slot is found.
  583. Arguments:
  584. defconfig: defconfig name to be put into.
  585. Returns:
  586. Return True on success or False on failure
  587. """
  588. for slot in self.slots:
  589. if slot.add(defconfig):
  590. return True
  591. return False
  592. def available(self):
  593. """Check if there is a vacant slot.
  594. Returns:
  595. Return True if at lease one vacant slot is found, False otherwise.
  596. """
  597. for slot in self.slots:
  598. if slot.poll():
  599. return True
  600. return False
  601. def empty(self):
  602. """Check if all slots are vacant.
  603. Returns:
  604. Return True if all the slots are vacant, False otherwise.
  605. """
  606. ret = True
  607. for slot in self.slots:
  608. if not slot.poll():
  609. ret = False
  610. return ret
  611. def show_failed_boards(self):
  612. """Display all of the failed boards (defconfigs)."""
  613. failed_boards = []
  614. for slot in self.slots:
  615. failed_boards += slot.get_failed_boards()
  616. if len(failed_boards) > 0:
  617. msg = [ "The following boards were not processed due to error:" ]
  618. msg += failed_boards
  619. for line in msg:
  620. print >> sys.stderr, color_text(self.options.color,
  621. COLOR_LIGHT_RED, line)
  622. with open('moveconfig.failed', 'w') as f:
  623. for board in failed_boards:
  624. f.write(board + '\n')
  625. def move_config(configs, options):
  626. """Move config options to defconfig files.
  627. Arguments:
  628. configs: A list of CONFIGs to move.
  629. options: option flags
  630. """
  631. if len(configs) == 0:
  632. print 'Nothing to do. exit.'
  633. sys.exit(0)
  634. print 'Move %s (jobs: %d)' % (', '.join(configs), options.jobs)
  635. if options.defconfigs:
  636. defconfigs = [line.strip() for line in open(options.defconfigs)]
  637. for i, defconfig in enumerate(defconfigs):
  638. if not defconfig.endswith('_defconfig'):
  639. defconfigs[i] = defconfig + '_defconfig'
  640. if not os.path.exists(os.path.join('configs', defconfigs[i])):
  641. sys.exit('%s - defconfig does not exist. Stopping.' %
  642. defconfigs[i])
  643. else:
  644. # All the defconfig files to be processed
  645. defconfigs = []
  646. for (dirpath, dirnames, filenames) in os.walk('configs'):
  647. dirpath = dirpath[len('configs') + 1:]
  648. for filename in fnmatch.filter(filenames, '*_defconfig'):
  649. defconfigs.append(os.path.join(dirpath, filename))
  650. progress = Progress(len(defconfigs))
  651. slots = Slots(configs, options, progress)
  652. # Main loop to process defconfig files:
  653. # Add a new subprocess into a vacant slot.
  654. # Sleep if there is no available slot.
  655. for defconfig in defconfigs:
  656. while not slots.add(defconfig):
  657. while not slots.available():
  658. # No available slot: sleep for a while
  659. time.sleep(SLEEP_TIME)
  660. # wait until all the subprocesses finish
  661. while not slots.empty():
  662. time.sleep(SLEEP_TIME)
  663. print ''
  664. slots.show_failed_boards()
  665. def main():
  666. try:
  667. cpu_count = multiprocessing.cpu_count()
  668. except NotImplementedError:
  669. cpu_count = 1
  670. parser = optparse.OptionParser()
  671. # Add options here
  672. parser.add_option('-c', '--color', action='store_true', default=False,
  673. help='display the log in color')
  674. parser.add_option('-d', '--defconfigs', type='string',
  675. help='a file containing a list of defconfigs to move')
  676. parser.add_option('-n', '--dry-run', action='store_true', default=False,
  677. help='perform a trial run (show log with no changes)')
  678. parser.add_option('-e', '--exit-on-error', action='store_true',
  679. default=False,
  680. help='exit immediately on any error')
  681. parser.add_option('-H', '--headers-only', dest='cleanup_headers_only',
  682. action='store_true', default=False,
  683. help='only cleanup the headers')
  684. parser.add_option('-j', '--jobs', type='int', default=cpu_count,
  685. help='the number of jobs to run simultaneously')
  686. parser.add_option('-v', '--verbose', action='store_true', default=False,
  687. help='show any build errors as boards are built')
  688. parser.usage += ' CONFIG ...'
  689. (options, configs) = parser.parse_args()
  690. if len(configs) == 0:
  691. parser.print_usage()
  692. sys.exit(1)
  693. # prefix the option name with CONFIG_ if missing
  694. configs = [ config if config.startswith('CONFIG_') else 'CONFIG_' + config
  695. for config in configs ]
  696. check_top_directory()
  697. check_clean_directory()
  698. update_cross_compile(options.color)
  699. if not options.cleanup_headers_only:
  700. move_config(configs, options)
  701. cleanup_headers(configs, options.dry_run)
  702. if __name__ == '__main__':
  703. main()