moveconfig.py 28 KB

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