moveconfig.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960
  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. -s, --force-sync
  98. Do "make savedefconfig" forcibly for all the defconfig files.
  99. If not specified, "make savedefconfig" only occurs for cases
  100. where at least one CONFIG was moved.
  101. -H, --headers-only
  102. Only cleanup the headers; skip the defconfig processing
  103. -j, --jobs
  104. Specify the number of threads to run simultaneously. If not specified,
  105. the number of threads is the same as the number of CPU cores.
  106. -v, --verbose
  107. Show any build errors as boards are built
  108. To see the complete list of supported options, run
  109. $ tools/moveconfig.py -h
  110. """
  111. import filecmp
  112. import fnmatch
  113. import multiprocessing
  114. import optparse
  115. import os
  116. import re
  117. import shutil
  118. import subprocess
  119. import sys
  120. import tempfile
  121. import time
  122. SHOW_GNU_MAKE = 'scripts/show-gnu-make'
  123. SLEEP_TIME=0.03
  124. # Here is the list of cross-tools I use.
  125. # Most of them are available at kernel.org
  126. # (https://www.kernel.org/pub/tools/crosstool/files/bin/), except the followings:
  127. # arc: https://github.com/foss-for-synopsys-dwc-arc-processors/toolchain/releases
  128. # blackfin: http://sourceforge.net/projects/adi-toolchain/files/
  129. # nds32: http://osdk.andestech.com/packages/nds32le-linux-glibc-v1.tgz
  130. # nios2: https://sourcery.mentor.com/GNUToolchain/subscription42545
  131. # sh: http://sourcery.mentor.com/public/gnu_toolchain/sh-linux-gnu
  132. #
  133. # openrisc kernel.org toolchain is out of date, download latest one from
  134. # http://opencores.org/or1k/OpenRISC_GNU_tool_chain#Prebuilt_versions
  135. CROSS_COMPILE = {
  136. 'arc': 'arc-linux-',
  137. 'aarch64': 'aarch64-linux-',
  138. 'arm': 'arm-unknown-linux-gnueabi-',
  139. 'avr32': 'avr32-linux-',
  140. 'blackfin': 'bfin-elf-',
  141. 'm68k': 'm68k-linux-',
  142. 'microblaze': 'microblaze-linux-',
  143. 'mips': 'mips-linux-',
  144. 'nds32': 'nds32le-linux-',
  145. 'nios2': 'nios2-linux-gnu-',
  146. 'openrisc': 'or1k-elf-',
  147. 'powerpc': 'powerpc-linux-',
  148. 'sh': 'sh-linux-gnu-',
  149. 'sparc': 'sparc-linux-',
  150. 'x86': 'i386-linux-'
  151. }
  152. STATE_IDLE = 0
  153. STATE_DEFCONFIG = 1
  154. STATE_AUTOCONF = 2
  155. STATE_SAVEDEFCONFIG = 3
  156. ACTION_MOVE = 0
  157. ACTION_NO_ENTRY = 1
  158. ACTION_NO_CHANGE = 2
  159. COLOR_BLACK = '0;30'
  160. COLOR_RED = '0;31'
  161. COLOR_GREEN = '0;32'
  162. COLOR_BROWN = '0;33'
  163. COLOR_BLUE = '0;34'
  164. COLOR_PURPLE = '0;35'
  165. COLOR_CYAN = '0;36'
  166. COLOR_LIGHT_GRAY = '0;37'
  167. COLOR_DARK_GRAY = '1;30'
  168. COLOR_LIGHT_RED = '1;31'
  169. COLOR_LIGHT_GREEN = '1;32'
  170. COLOR_YELLOW = '1;33'
  171. COLOR_LIGHT_BLUE = '1;34'
  172. COLOR_LIGHT_PURPLE = '1;35'
  173. COLOR_LIGHT_CYAN = '1;36'
  174. COLOR_WHITE = '1;37'
  175. ### helper functions ###
  176. def get_devnull():
  177. """Get the file object of '/dev/null' device."""
  178. try:
  179. devnull = subprocess.DEVNULL # py3k
  180. except AttributeError:
  181. devnull = open(os.devnull, 'wb')
  182. return devnull
  183. def check_top_directory():
  184. """Exit if we are not at the top of source directory."""
  185. for f in ('README', 'Licenses'):
  186. if not os.path.exists(f):
  187. sys.exit('Please run at the top of source directory.')
  188. def check_clean_directory():
  189. """Exit if the source tree is not clean."""
  190. for f in ('.config', 'include/config'):
  191. if os.path.exists(f):
  192. sys.exit("source tree is not clean, please run 'make mrproper'")
  193. def get_make_cmd():
  194. """Get the command name of GNU Make.
  195. U-Boot needs GNU Make for building, but the command name is not
  196. necessarily "make". (for example, "gmake" on FreeBSD).
  197. Returns the most appropriate command name on your system.
  198. """
  199. process = subprocess.Popen([SHOW_GNU_MAKE], stdout=subprocess.PIPE)
  200. ret = process.communicate()
  201. if process.returncode:
  202. sys.exit('GNU Make not found')
  203. return ret[0].rstrip()
  204. def color_text(color_enabled, color, string):
  205. """Return colored string."""
  206. if color_enabled:
  207. # LF should not be surrounded by the escape sequence.
  208. # Otherwise, additional whitespace or line-feed might be printed.
  209. return '\n'.join([ '\033[' + color + 'm' + s + '\033[0m' if s else ''
  210. for s in string.split('\n') ])
  211. else:
  212. return string
  213. def update_cross_compile(color_enabled):
  214. """Update per-arch CROSS_COMPILE via environment variables
  215. The default CROSS_COMPILE values are available
  216. in the CROSS_COMPILE list above.
  217. You can override them via environment variables
  218. CROSS_COMPILE_{ARCH}.
  219. For example, if you want to override toolchain prefixes
  220. for ARM and PowerPC, you can do as follows in your shell:
  221. export CROSS_COMPILE_ARM=...
  222. export CROSS_COMPILE_POWERPC=...
  223. Then, this function checks if specified compilers really exist in your
  224. PATH environment.
  225. """
  226. archs = []
  227. for arch in os.listdir('arch'):
  228. if os.path.exists(os.path.join('arch', arch, 'Makefile')):
  229. archs.append(arch)
  230. # arm64 is a special case
  231. archs.append('aarch64')
  232. for arch in archs:
  233. env = 'CROSS_COMPILE_' + arch.upper()
  234. cross_compile = os.environ.get(env)
  235. if not cross_compile:
  236. cross_compile = CROSS_COMPILE.get(arch, '')
  237. for path in os.environ["PATH"].split(os.pathsep):
  238. gcc_path = os.path.join(path, cross_compile + 'gcc')
  239. if os.path.isfile(gcc_path) and os.access(gcc_path, os.X_OK):
  240. break
  241. else:
  242. print >> sys.stderr, color_text(color_enabled, COLOR_YELLOW,
  243. 'warning: %sgcc: not found in PATH. %s architecture boards will be skipped'
  244. % (cross_compile, arch))
  245. cross_compile = None
  246. CROSS_COMPILE[arch] = cross_compile
  247. def cleanup_one_header(header_path, patterns, dry_run):
  248. """Clean regex-matched lines away from a file.
  249. Arguments:
  250. header_path: path to the cleaned file.
  251. patterns: list of regex patterns. Any lines matching to these
  252. patterns are deleted.
  253. dry_run: make no changes, but still display log.
  254. """
  255. with open(header_path) as f:
  256. lines = f.readlines()
  257. matched = []
  258. for i, line in enumerate(lines):
  259. for pattern in patterns:
  260. m = pattern.search(line)
  261. if m:
  262. print '%s: %s: %s' % (header_path, i + 1, line),
  263. matched.append(i)
  264. break
  265. if dry_run or not matched:
  266. return
  267. with open(header_path, 'w') as f:
  268. for i, line in enumerate(lines):
  269. if not i in matched:
  270. f.write(line)
  271. def cleanup_headers(configs, dry_run):
  272. """Delete config defines from board headers.
  273. Arguments:
  274. configs: A list of CONFIGs to remove.
  275. dry_run: make no changes, but still display log.
  276. """
  277. while True:
  278. choice = raw_input('Clean up headers? [y/n]: ').lower()
  279. print choice
  280. if choice == 'y' or choice == 'n':
  281. break
  282. if choice == 'n':
  283. return
  284. patterns = []
  285. for config in configs:
  286. patterns.append(re.compile(r'#\s*define\s+%s\W' % config))
  287. patterns.append(re.compile(r'#\s*undef\s+%s\W' % config))
  288. for dir in 'include', 'arch', 'board':
  289. for (dirpath, dirnames, filenames) in os.walk(dir):
  290. for filename in filenames:
  291. if not fnmatch.fnmatch(filename, '*~'):
  292. cleanup_one_header(os.path.join(dirpath, filename),
  293. patterns, dry_run)
  294. ### classes ###
  295. class Progress:
  296. """Progress Indicator"""
  297. def __init__(self, total):
  298. """Create a new progress indicator.
  299. Arguments:
  300. total: A number of defconfig files to process.
  301. """
  302. self.current = 0
  303. self.total = total
  304. def inc(self):
  305. """Increment the number of processed defconfig files."""
  306. self.current += 1
  307. def show(self):
  308. """Display the progress."""
  309. print ' %d defconfigs out of %d\r' % (self.current, self.total),
  310. sys.stdout.flush()
  311. class KconfigParser:
  312. """A parser of .config and include/autoconf.mk."""
  313. re_arch = re.compile(r'CONFIG_SYS_ARCH="(.*)"')
  314. re_cpu = re.compile(r'CONFIG_SYS_CPU="(.*)"')
  315. def __init__(self, configs, options, build_dir):
  316. """Create a new parser.
  317. Arguments:
  318. configs: A list of CONFIGs to move.
  319. options: option flags.
  320. build_dir: Build directory.
  321. """
  322. self.configs = configs
  323. self.options = options
  324. self.dotconfig = os.path.join(build_dir, '.config')
  325. self.autoconf = os.path.join(build_dir, 'include', 'autoconf.mk')
  326. self.config_autoconf = os.path.join(build_dir, 'include', 'config',
  327. 'auto.conf')
  328. self.defconfig = os.path.join(build_dir, 'defconfig')
  329. def get_cross_compile(self):
  330. """Parse .config file and return CROSS_COMPILE.
  331. Returns:
  332. A string storing the compiler prefix for the architecture.
  333. Return a NULL string for architectures that do not require
  334. compiler prefix (Sandbox and native build is the case).
  335. Return None if the specified compiler is missing in your PATH.
  336. Caller should distinguish '' and None.
  337. """
  338. arch = ''
  339. cpu = ''
  340. for line in open(self.dotconfig):
  341. m = self.re_arch.match(line)
  342. if m:
  343. arch = m.group(1)
  344. continue
  345. m = self.re_cpu.match(line)
  346. if m:
  347. cpu = m.group(1)
  348. if not arch:
  349. return None
  350. # fix-up for aarch64
  351. if arch == 'arm' and cpu == 'armv8':
  352. arch = 'aarch64'
  353. return CROSS_COMPILE.get(arch, None)
  354. def parse_one_config(self, config, dotconfig_lines, autoconf_lines):
  355. """Parse .config, defconfig, include/autoconf.mk for one config.
  356. This function looks for the config options in the lines from
  357. defconfig, .config, and include/autoconf.mk in order to decide
  358. which action should be taken for this defconfig.
  359. Arguments:
  360. config: CONFIG name to parse.
  361. dotconfig_lines: lines from the .config file.
  362. autoconf_lines: lines from the include/autoconf.mk file.
  363. Returns:
  364. A tupple of the action for this defconfig and the line
  365. matched for the config.
  366. """
  367. not_set = '# %s is not set' % config
  368. for line in dotconfig_lines:
  369. line = line.rstrip()
  370. if line.startswith(config + '=') or line == not_set:
  371. old_val = line
  372. break
  373. else:
  374. return (ACTION_NO_ENTRY, config)
  375. for line in autoconf_lines:
  376. line = line.rstrip()
  377. if line.startswith(config + '='):
  378. new_val = line
  379. break
  380. else:
  381. new_val = not_set
  382. if old_val == new_val:
  383. return (ACTION_NO_CHANGE, new_val)
  384. # If this CONFIG is neither bool nor trisate
  385. if old_val[-2:] != '=y' and old_val[-2:] != '=m' and old_val != not_set:
  386. # tools/scripts/define2mk.sed changes '1' to 'y'.
  387. # This is a problem if the CONFIG is int type.
  388. # Check the type in Kconfig and handle it correctly.
  389. if new_val[-2:] == '=y':
  390. new_val = new_val[:-1] + '1'
  391. return (ACTION_MOVE, new_val)
  392. def update_dotconfig(self):
  393. """Parse files for the config options and update the .config.
  394. This function parses the generated .config and include/autoconf.mk
  395. searching the target options.
  396. Move the config option(s) to the .config as needed.
  397. Arguments:
  398. defconfig: defconfig name.
  399. Returns:
  400. Return a tuple of (updated flag, log string).
  401. The "updated flag" is True if the .config was updated, False
  402. otherwise. The "log string" shows what happend to the .config.
  403. """
  404. results = []
  405. updated = False
  406. with open(self.dotconfig) as f:
  407. dotconfig_lines = f.readlines()
  408. with open(self.autoconf) as f:
  409. autoconf_lines = f.readlines()
  410. for config in self.configs:
  411. result = self.parse_one_config(config, dotconfig_lines,
  412. autoconf_lines)
  413. results.append(result)
  414. log = ''
  415. for (action, value) in results:
  416. if action == ACTION_MOVE:
  417. actlog = "Move '%s'" % value
  418. log_color = COLOR_LIGHT_GREEN
  419. elif action == ACTION_NO_ENTRY:
  420. actlog = "%s is not defined in Kconfig. Do nothing." % value
  421. log_color = COLOR_LIGHT_BLUE
  422. elif action == ACTION_NO_CHANGE:
  423. actlog = "'%s' is the same as the define in Kconfig. Do nothing." \
  424. % value
  425. log_color = COLOR_LIGHT_PURPLE
  426. else:
  427. sys.exit("Internal Error. This should not happen.")
  428. log += color_text(self.options.color, log_color, actlog) + '\n'
  429. with open(self.dotconfig, 'a') as f:
  430. for (action, value) in results:
  431. if action == ACTION_MOVE:
  432. f.write(value + '\n')
  433. updated = True
  434. self.results = results
  435. os.remove(self.config_autoconf)
  436. os.remove(self.autoconf)
  437. return (updated, log)
  438. def check_defconfig(self):
  439. """Check the defconfig after savedefconfig
  440. Returns:
  441. Return additional log if moved CONFIGs were removed again by
  442. 'make savedefconfig'.
  443. """
  444. log = ''
  445. with open(self.defconfig) as f:
  446. defconfig_lines = f.readlines()
  447. for (action, value) in self.results:
  448. if action != ACTION_MOVE:
  449. continue
  450. if not value + '\n' in defconfig_lines:
  451. log += color_text(self.options.color, COLOR_YELLOW,
  452. "'%s' was removed by savedefconfig.\n" %
  453. value)
  454. return log
  455. class Slot:
  456. """A slot to store a subprocess.
  457. Each instance of this class handles one subprocess.
  458. This class is useful to control multiple threads
  459. for faster processing.
  460. """
  461. def __init__(self, configs, options, progress, devnull, make_cmd):
  462. """Create a new process slot.
  463. Arguments:
  464. configs: A list of CONFIGs to move.
  465. options: option flags.
  466. progress: A progress indicator.
  467. devnull: A file object of '/dev/null'.
  468. make_cmd: command name of GNU Make.
  469. """
  470. self.options = options
  471. self.progress = progress
  472. self.build_dir = tempfile.mkdtemp()
  473. self.devnull = devnull
  474. self.make_cmd = (make_cmd, 'O=' + self.build_dir)
  475. self.parser = KconfigParser(configs, options, self.build_dir)
  476. self.state = STATE_IDLE
  477. self.failed_boards = []
  478. def __del__(self):
  479. """Delete the working directory
  480. This function makes sure the temporary directory is cleaned away
  481. even if Python suddenly dies due to error. It should be done in here
  482. because it is guaranteed the destructor is always invoked when the
  483. instance of the class gets unreferenced.
  484. If the subprocess is still running, wait until it finishes.
  485. """
  486. if self.state != STATE_IDLE:
  487. while self.ps.poll() == None:
  488. pass
  489. shutil.rmtree(self.build_dir)
  490. def add(self, defconfig):
  491. """Assign a new subprocess for defconfig and add it to the slot.
  492. If the slot is vacant, create a new subprocess for processing the
  493. given defconfig and add it to the slot. Just returns False if
  494. the slot is occupied (i.e. the current subprocess is still running).
  495. Arguments:
  496. defconfig: defconfig name.
  497. Returns:
  498. Return True on success or False on failure
  499. """
  500. if self.state != STATE_IDLE:
  501. return False
  502. self.defconfig = defconfig
  503. self.log = ''
  504. self.do_defconfig()
  505. return True
  506. def poll(self):
  507. """Check the status of the subprocess and handle it as needed.
  508. Returns True if the slot is vacant (i.e. in idle state).
  509. If the configuration is successfully finished, assign a new
  510. subprocess to build include/autoconf.mk.
  511. If include/autoconf.mk is generated, invoke the parser to
  512. parse the .config and the include/autoconf.mk, moving
  513. config options to the .config as needed.
  514. If the .config was updated, run "make savedefconfig" to sync
  515. it, update the original defconfig, and then set the slot back
  516. to the idle state.
  517. Returns:
  518. Return True if the subprocess is terminated, False otherwise
  519. """
  520. if self.state == STATE_IDLE:
  521. return True
  522. if self.ps.poll() == None:
  523. return False
  524. if self.ps.poll() != 0:
  525. self.handle_error()
  526. elif self.state == STATE_DEFCONFIG:
  527. self.do_autoconf()
  528. elif self.state == STATE_AUTOCONF:
  529. self.do_savedefconfig()
  530. elif self.state == STATE_SAVEDEFCONFIG:
  531. self.update_defconfig()
  532. else:
  533. sys.exit("Internal Error. This should not happen.")
  534. return True if self.state == STATE_IDLE else False
  535. def handle_error(self):
  536. """Handle error cases."""
  537. self.log += color_text(self.options.color, COLOR_LIGHT_RED,
  538. "Failed to process.\n")
  539. if self.options.verbose:
  540. self.log += color_text(self.options.color, COLOR_LIGHT_CYAN,
  541. self.ps.stderr.read())
  542. self.finish(False)
  543. def do_defconfig(self):
  544. """Run 'make <board>_defconfig' to create the .config file."""
  545. cmd = list(self.make_cmd)
  546. cmd.append(self.defconfig)
  547. self.ps = subprocess.Popen(cmd, stdout=self.devnull,
  548. stderr=subprocess.PIPE)
  549. self.state = STATE_DEFCONFIG
  550. def do_autoconf(self):
  551. """Run 'make include/config/auto.conf'."""
  552. self.cross_compile = self.parser.get_cross_compile()
  553. if self.cross_compile is None:
  554. self.log += color_text(self.options.color, COLOR_YELLOW,
  555. "Compiler is missing. Do nothing.\n")
  556. self.finish(False)
  557. return
  558. cmd = list(self.make_cmd)
  559. if self.cross_compile:
  560. cmd.append('CROSS_COMPILE=%s' % self.cross_compile)
  561. cmd.append('KCONFIG_IGNORE_DUPLICATES=1')
  562. cmd.append('include/config/auto.conf')
  563. self.ps = subprocess.Popen(cmd, stdout=self.devnull,
  564. stderr=subprocess.PIPE)
  565. self.state = STATE_AUTOCONF
  566. def do_savedefconfig(self):
  567. """Update the .config and run 'make savedefconfig'."""
  568. (updated, log) = self.parser.update_dotconfig()
  569. self.log += log
  570. if not self.options.force_sync and not updated:
  571. self.finish(True)
  572. return
  573. if updated:
  574. self.log += color_text(self.options.color, COLOR_LIGHT_GREEN,
  575. "Syncing by savedefconfig...\n")
  576. else:
  577. self.log += "Syncing by savedefconfig (forced by option)...\n"
  578. cmd = list(self.make_cmd)
  579. cmd.append('savedefconfig')
  580. self.ps = subprocess.Popen(cmd, stdout=self.devnull,
  581. stderr=subprocess.PIPE)
  582. self.state = STATE_SAVEDEFCONFIG
  583. def update_defconfig(self):
  584. """Update the input defconfig and go back to the idle state."""
  585. self.log += self.parser.check_defconfig()
  586. orig_defconfig = os.path.join('configs', self.defconfig)
  587. new_defconfig = os.path.join(self.build_dir, 'defconfig')
  588. updated = not filecmp.cmp(orig_defconfig, new_defconfig)
  589. if updated:
  590. self.log += color_text(self.options.color, COLOR_LIGHT_BLUE,
  591. "defconfig was updated.\n")
  592. if not self.options.dry_run and updated:
  593. shutil.move(new_defconfig, orig_defconfig)
  594. self.finish(True)
  595. def finish(self, success):
  596. """Display log along with progress and go to the idle state.
  597. Arguments:
  598. success: Should be True when the defconfig was processed
  599. successfully, or False when it fails.
  600. """
  601. # output at least 30 characters to hide the "* defconfigs out of *".
  602. log = self.defconfig.ljust(30) + '\n'
  603. log += '\n'.join([ ' ' + s for s in self.log.split('\n') ])
  604. # Some threads are running in parallel.
  605. # Print log atomically to not mix up logs from different threads.
  606. print >> (sys.stdout if success else sys.stderr), log
  607. if not success:
  608. if self.options.exit_on_error:
  609. sys.exit("Exit on error.")
  610. # If --exit-on-error flag is not set, skip this board and continue.
  611. # Record the failed board.
  612. self.failed_boards.append(self.defconfig)
  613. self.progress.inc()
  614. self.progress.show()
  615. self.state = STATE_IDLE
  616. def get_failed_boards(self):
  617. """Returns a list of failed boards (defconfigs) in this slot.
  618. """
  619. return self.failed_boards
  620. class Slots:
  621. """Controller of the array of subprocess slots."""
  622. def __init__(self, configs, options, progress):
  623. """Create a new slots controller.
  624. Arguments:
  625. configs: A list of CONFIGs to move.
  626. options: option flags.
  627. progress: A progress indicator.
  628. """
  629. self.options = options
  630. self.slots = []
  631. devnull = get_devnull()
  632. make_cmd = get_make_cmd()
  633. for i in range(options.jobs):
  634. self.slots.append(Slot(configs, options, progress, devnull,
  635. make_cmd))
  636. def add(self, defconfig):
  637. """Add a new subprocess if a vacant slot is found.
  638. Arguments:
  639. defconfig: defconfig name to be put into.
  640. Returns:
  641. Return True on success or False on failure
  642. """
  643. for slot in self.slots:
  644. if slot.add(defconfig):
  645. return True
  646. return False
  647. def available(self):
  648. """Check if there is a vacant slot.
  649. Returns:
  650. Return True if at lease one vacant slot is found, False otherwise.
  651. """
  652. for slot in self.slots:
  653. if slot.poll():
  654. return True
  655. return False
  656. def empty(self):
  657. """Check if all slots are vacant.
  658. Returns:
  659. Return True if all the slots are vacant, False otherwise.
  660. """
  661. ret = True
  662. for slot in self.slots:
  663. if not slot.poll():
  664. ret = False
  665. return ret
  666. def show_failed_boards(self):
  667. """Display all of the failed boards (defconfigs)."""
  668. failed_boards = []
  669. for slot in self.slots:
  670. failed_boards += slot.get_failed_boards()
  671. if len(failed_boards) > 0:
  672. msg = [ "The following boards were not processed due to error:" ]
  673. msg += failed_boards
  674. for line in msg:
  675. print >> sys.stderr, color_text(self.options.color,
  676. COLOR_LIGHT_RED, line)
  677. with open('moveconfig.failed', 'w') as f:
  678. for board in failed_boards:
  679. f.write(board + '\n')
  680. def move_config(configs, options):
  681. """Move config options to defconfig files.
  682. Arguments:
  683. configs: A list of CONFIGs to move.
  684. options: option flags
  685. """
  686. if len(configs) == 0:
  687. if options.force_sync:
  688. print 'No CONFIG is specified. You are probably syncing defconfigs.',
  689. else:
  690. print 'Neither CONFIG nor --force-sync is specified. Nothing will happen.',
  691. else:
  692. print 'Move ' + ', '.join(configs),
  693. print '(jobs: %d)\n' % options.jobs
  694. if options.defconfigs:
  695. defconfigs = [line.strip() for line in open(options.defconfigs)]
  696. for i, defconfig in enumerate(defconfigs):
  697. if not defconfig.endswith('_defconfig'):
  698. defconfigs[i] = defconfig + '_defconfig'
  699. if not os.path.exists(os.path.join('configs', defconfigs[i])):
  700. sys.exit('%s - defconfig does not exist. Stopping.' %
  701. defconfigs[i])
  702. else:
  703. # All the defconfig files to be processed
  704. defconfigs = []
  705. for (dirpath, dirnames, filenames) in os.walk('configs'):
  706. dirpath = dirpath[len('configs') + 1:]
  707. for filename in fnmatch.filter(filenames, '*_defconfig'):
  708. defconfigs.append(os.path.join(dirpath, filename))
  709. progress = Progress(len(defconfigs))
  710. slots = Slots(configs, options, progress)
  711. # Main loop to process defconfig files:
  712. # Add a new subprocess into a vacant slot.
  713. # Sleep if there is no available slot.
  714. for defconfig in defconfigs:
  715. while not slots.add(defconfig):
  716. while not slots.available():
  717. # No available slot: sleep for a while
  718. time.sleep(SLEEP_TIME)
  719. # wait until all the subprocesses finish
  720. while not slots.empty():
  721. time.sleep(SLEEP_TIME)
  722. print ''
  723. slots.show_failed_boards()
  724. def main():
  725. try:
  726. cpu_count = multiprocessing.cpu_count()
  727. except NotImplementedError:
  728. cpu_count = 1
  729. parser = optparse.OptionParser()
  730. # Add options here
  731. parser.add_option('-c', '--color', action='store_true', default=False,
  732. help='display the log in color')
  733. parser.add_option('-d', '--defconfigs', type='string',
  734. help='a file containing a list of defconfigs to move')
  735. parser.add_option('-n', '--dry-run', action='store_true', default=False,
  736. help='perform a trial run (show log with no changes)')
  737. parser.add_option('-e', '--exit-on-error', action='store_true',
  738. default=False,
  739. help='exit immediately on any error')
  740. parser.add_option('-s', '--force-sync', action='store_true', default=False,
  741. help='force sync by savedefconfig')
  742. parser.add_option('-H', '--headers-only', dest='cleanup_headers_only',
  743. action='store_true', default=False,
  744. help='only cleanup the headers')
  745. parser.add_option('-j', '--jobs', type='int', default=cpu_count,
  746. help='the number of jobs to run simultaneously')
  747. parser.add_option('-v', '--verbose', action='store_true', default=False,
  748. help='show any build errors as boards are built')
  749. parser.usage += ' CONFIG ...'
  750. (options, configs) = parser.parse_args()
  751. if len(configs) == 0 and not options.force_sync:
  752. parser.print_usage()
  753. sys.exit(1)
  754. # prefix the option name with CONFIG_ if missing
  755. configs = [ config if config.startswith('CONFIG_') else 'CONFIG_' + config
  756. for config in configs ]
  757. check_top_directory()
  758. check_clean_directory()
  759. update_cross_compile(options.color)
  760. if not options.cleanup_headers_only:
  761. move_config(configs, options)
  762. if configs:
  763. cleanup_headers(configs, options.dry_run)
  764. if __name__ == '__main__':
  765. main()