moveconfig.py 29 KB

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