moveconfig.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892
  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. -H, --headers-only
  107. Only cleanup the headers; skip the defconfig processing
  108. -j, --jobs
  109. Specify the number of threads to run simultaneously. If not specified,
  110. the number of threads is the same as the number of CPU cores.
  111. To see the complete list of supported options, run
  112. $ tools/moveconfig.py -h
  113. """
  114. import fnmatch
  115. import multiprocessing
  116. import optparse
  117. import os
  118. import re
  119. import shutil
  120. import subprocess
  121. import sys
  122. import tempfile
  123. import time
  124. SHOW_GNU_MAKE = 'scripts/show-gnu-make'
  125. SLEEP_TIME=0.03
  126. # Here is the list of cross-tools I use.
  127. # Most of them are available at kernel.org
  128. # (https://www.kernel.org/pub/tools/crosstool/files/bin/), except the followings:
  129. # arc: https://github.com/foss-for-synopsys-dwc-arc-processors/toolchain/releases
  130. # blackfin: http://sourceforge.net/projects/adi-toolchain/files/
  131. # nds32: http://osdk.andestech.com/packages/
  132. # nios2: https://sourcery.mentor.com/GNUToolchain/subscription42545
  133. # sh: http://sourcery.mentor.com/public/gnu_toolchain/sh-linux-gnu
  134. CROSS_COMPILE = {
  135. 'arc': 'arc-linux-',
  136. 'aarch64': 'aarch64-linux-',
  137. 'arm': 'arm-unknown-linux-gnueabi-',
  138. 'avr32': 'avr32-linux-',
  139. 'blackfin': 'bfin-elf-',
  140. 'm68k': 'm68k-linux-',
  141. 'microblaze': 'microblaze-linux-',
  142. 'mips': 'mips-linux-',
  143. 'nds32': 'nds32le-linux-',
  144. 'nios2': 'nios2-linux-gnu-',
  145. 'openrisc': 'or32-linux-',
  146. 'powerpc': 'powerpc-linux-',
  147. 'sh': 'sh-linux-gnu-',
  148. 'sparc': 'sparc-linux-',
  149. 'x86': 'i386-linux-'
  150. }
  151. STATE_IDLE = 0
  152. STATE_DEFCONFIG = 1
  153. STATE_AUTOCONF = 2
  154. STATE_SAVEDEFCONFIG = 3
  155. ACTION_MOVE = 0
  156. ACTION_DEFAULT_VALUE = 1
  157. ACTION_ALREADY_EXIST = 2
  158. ACTION_UNDEFINED = 3
  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 get_make_cmd():
  189. """Get the command name of GNU Make.
  190. U-Boot needs GNU Make for building, but the command name is not
  191. necessarily "make". (for example, "gmake" on FreeBSD).
  192. Returns the most appropriate command name on your system.
  193. """
  194. process = subprocess.Popen([SHOW_GNU_MAKE], stdout=subprocess.PIPE)
  195. ret = process.communicate()
  196. if process.returncode:
  197. sys.exit('GNU Make not found')
  198. return ret[0].rstrip()
  199. def color_text(color_enabled, color, string):
  200. """Return colored string."""
  201. if color_enabled:
  202. return '\033[' + color + 'm' + string + '\033[0m'
  203. else:
  204. return string
  205. def log_msg(color_enabled, color, defconfig, msg):
  206. """Return the formated line for the log."""
  207. return defconfig[:-len('_defconfig')].ljust(37) + ': ' + \
  208. color_text(color_enabled, color, msg) + '\n'
  209. def update_cross_compile():
  210. """Update per-arch CROSS_COMPILE via enviroment variables
  211. The default CROSS_COMPILE values are available
  212. in the CROSS_COMPILE list above.
  213. You can override them via enviroment variables
  214. CROSS_COMPILE_{ARCH}.
  215. For example, if you want to override toolchain prefixes
  216. for ARM and PowerPC, you can do as follows in your shell:
  217. export CROSS_COMPILE_ARM=...
  218. export CROSS_COMPILE_POWERPC=...
  219. """
  220. archs = []
  221. for arch in os.listdir('arch'):
  222. if os.path.exists(os.path.join('arch', arch, 'Makefile')):
  223. archs.append(arch)
  224. # arm64 is a special case
  225. archs.append('aarch64')
  226. for arch in archs:
  227. env = 'CROSS_COMPILE_' + arch.upper()
  228. cross_compile = os.environ.get(env)
  229. if cross_compile:
  230. CROSS_COMPILE[arch] = cross_compile
  231. def cleanup_one_header(header_path, patterns, dry_run):
  232. """Clean regex-matched lines away from a file.
  233. Arguments:
  234. header_path: path to the cleaned file.
  235. patterns: list of regex patterns. Any lines matching to these
  236. patterns are deleted.
  237. dry_run: make no changes, but still display log.
  238. """
  239. with open(header_path) as f:
  240. lines = f.readlines()
  241. matched = []
  242. for i, line in enumerate(lines):
  243. for pattern in patterns:
  244. m = pattern.search(line)
  245. if m:
  246. print '%s: %s: %s' % (header_path, i + 1, line),
  247. matched.append(i)
  248. break
  249. if dry_run or not matched:
  250. return
  251. with open(header_path, 'w') as f:
  252. for i, line in enumerate(lines):
  253. if not i in matched:
  254. f.write(line)
  255. def cleanup_headers(config_attrs, dry_run):
  256. """Delete config defines from board headers.
  257. Arguments:
  258. config_attrs: A list of dictionaris, each of them includes the name,
  259. the type, and the default value of the target config.
  260. dry_run: make no changes, but still display log.
  261. """
  262. while True:
  263. choice = raw_input('Clean up headers? [y/n]: ').lower()
  264. print choice
  265. if choice == 'y' or choice == 'n':
  266. break
  267. if choice == 'n':
  268. return
  269. patterns = []
  270. for config_attr in config_attrs:
  271. config = config_attr['config']
  272. patterns.append(re.compile(r'#\s*define\s+%s\W' % config))
  273. patterns.append(re.compile(r'#\s*undef\s+%s\W' % config))
  274. for dir in 'include', 'arch', 'board':
  275. for (dirpath, dirnames, filenames) in os.walk(dir):
  276. for filename in filenames:
  277. if not fnmatch.fnmatch(filename, '*~'):
  278. cleanup_one_header(os.path.join(dirpath, filename),
  279. patterns, dry_run)
  280. ### classes ###
  281. class KconfigParser:
  282. """A parser of .config and include/autoconf.mk."""
  283. re_arch = re.compile(r'CONFIG_SYS_ARCH="(.*)"')
  284. re_cpu = re.compile(r'CONFIG_SYS_CPU="(.*)"')
  285. def __init__(self, config_attrs, options, build_dir):
  286. """Create a new parser.
  287. Arguments:
  288. config_attrs: A list of dictionaris, each of them includes the name,
  289. the type, and the default value of the target config.
  290. options: option flags.
  291. build_dir: Build directory.
  292. """
  293. self.config_attrs = config_attrs
  294. self.options = options
  295. self.build_dir = build_dir
  296. def get_cross_compile(self):
  297. """Parse .config file and return CROSS_COMPILE.
  298. Returns:
  299. A string storing the compiler prefix for the architecture.
  300. """
  301. arch = ''
  302. cpu = ''
  303. dotconfig = os.path.join(self.build_dir, '.config')
  304. for line in open(dotconfig):
  305. m = self.re_arch.match(line)
  306. if m:
  307. arch = m.group(1)
  308. continue
  309. m = self.re_cpu.match(line)
  310. if m:
  311. cpu = m.group(1)
  312. assert arch, 'Error: arch is not defined in %s' % defconfig
  313. # fix-up for aarch64
  314. if arch == 'arm' and cpu == 'armv8':
  315. arch = 'aarch64'
  316. return CROSS_COMPILE.get(arch, '')
  317. def parse_one_config(self, config_attr, defconfig_lines, autoconf_lines):
  318. """Parse .config, defconfig, include/autoconf.mk for one config.
  319. This function looks for the config options in the lines from
  320. defconfig, .config, and include/autoconf.mk in order to decide
  321. which action should be taken for this defconfig.
  322. Arguments:
  323. config_attr: A dictionary including the name, the type,
  324. and the default value of the target config.
  325. defconfig_lines: lines from the original defconfig file.
  326. autoconf_lines: lines from the include/autoconf.mk file.
  327. Returns:
  328. A tupple of the action for this defconfig and the line
  329. matched for the config.
  330. """
  331. config = config_attr['config']
  332. not_set = '# %s is not set' % config
  333. if config_attr['type'] in ('bool', 'tristate') and \
  334. config_attr['default'] == 'n':
  335. default = not_set
  336. else:
  337. default = config + '=' + config_attr['default']
  338. for line in defconfig_lines:
  339. line = line.rstrip()
  340. if line.startswith(config + '=') or line == not_set:
  341. return (ACTION_ALREADY_EXIST, line)
  342. if config_attr['type'] in ('bool', 'tristate'):
  343. value = not_set
  344. else:
  345. value = '(undefined)'
  346. for line in autoconf_lines:
  347. line = line.rstrip()
  348. if line.startswith(config + '='):
  349. value = line
  350. break
  351. if value == default:
  352. action = ACTION_DEFAULT_VALUE
  353. elif value == '(undefined)':
  354. action = ACTION_UNDEFINED
  355. else:
  356. action = ACTION_MOVE
  357. return (action, value)
  358. def update_defconfig(self, defconfig):
  359. """Parse files for the config options and update the defconfig.
  360. This function parses the given defconfig, the generated .config
  361. and include/autoconf.mk searching the target options.
  362. Move the config option(s) to the defconfig or do nothing if unneeded.
  363. Also, display the log to show what happened to this defconfig.
  364. Arguments:
  365. defconfig: defconfig name.
  366. """
  367. defconfig_path = os.path.join('configs', defconfig)
  368. dotconfig_path = os.path.join(self.build_dir, '.config')
  369. autoconf_path = os.path.join(self.build_dir, 'include', 'autoconf.mk')
  370. results = []
  371. with open(defconfig_path) as f:
  372. defconfig_lines = f.readlines()
  373. with open(autoconf_path) as f:
  374. autoconf_lines = f.readlines()
  375. for config_attr in self.config_attrs:
  376. result = self.parse_one_config(config_attr, defconfig_lines,
  377. autoconf_lines)
  378. results.append(result)
  379. log = ''
  380. for (action, value) in results:
  381. if action == ACTION_MOVE:
  382. actlog = "Move '%s'" % value
  383. log_color = COLOR_LIGHT_GREEN
  384. elif action == ACTION_DEFAULT_VALUE:
  385. actlog = "Default value '%s'. Do nothing." % value
  386. log_color = COLOR_LIGHT_BLUE
  387. elif action == ACTION_ALREADY_EXIST:
  388. actlog = "'%s' already defined in Kconfig. Do nothing." % value
  389. log_color = COLOR_LIGHT_PURPLE
  390. elif action == ACTION_UNDEFINED:
  391. actlog = "Undefined. Do nothing."
  392. log_color = COLOR_DARK_GRAY
  393. else:
  394. sys.exit("Internal Error. This should not happen.")
  395. log += log_msg(self.options.color, log_color, defconfig, actlog)
  396. # Some threads are running in parallel.
  397. # Print log in one shot to not mix up logs from different threads.
  398. print log,
  399. if not self.options.dry_run:
  400. with open(dotconfig_path, 'a') as f:
  401. for (action, value) in results:
  402. if action == ACTION_MOVE:
  403. f.write(value + '\n')
  404. os.remove(os.path.join(self.build_dir, 'include', 'config', 'auto.conf'))
  405. os.remove(autoconf_path)
  406. class Slot:
  407. """A slot to store a subprocess.
  408. Each instance of this class handles one subprocess.
  409. This class is useful to control multiple threads
  410. for faster processing.
  411. """
  412. def __init__(self, config_attrs, options, devnull, make_cmd):
  413. """Create a new process slot.
  414. Arguments:
  415. config_attrs: A list of dictionaris, each of them includes the name,
  416. the type, and the default value of the target config.
  417. options: option flags.
  418. devnull: A file object of '/dev/null'.
  419. make_cmd: command name of GNU Make.
  420. """
  421. self.options = options
  422. self.build_dir = tempfile.mkdtemp()
  423. self.devnull = devnull
  424. self.make_cmd = (make_cmd, 'O=' + self.build_dir)
  425. self.parser = KconfigParser(config_attrs, options, self.build_dir)
  426. self.state = STATE_IDLE
  427. self.failed_boards = []
  428. def __del__(self):
  429. """Delete the working directory
  430. This function makes sure the temporary directory is cleaned away
  431. even if Python suddenly dies due to error. It should be done in here
  432. because it is guranteed the destructor is always invoked when the
  433. instance of the class gets unreferenced.
  434. If the subprocess is still running, wait until it finishes.
  435. """
  436. if self.state != STATE_IDLE:
  437. while self.ps.poll() == None:
  438. pass
  439. shutil.rmtree(self.build_dir)
  440. def add(self, defconfig):
  441. """Assign a new subprocess for defconfig and add it to the slot.
  442. If the slot is vacant, create a new subprocess for processing the
  443. given defconfig and add it to the slot. Just returns False if
  444. the slot is occupied (i.e. the current subprocess is still running).
  445. Arguments:
  446. defconfig: defconfig name.
  447. Returns:
  448. Return True on success or False on failure
  449. """
  450. if self.state != STATE_IDLE:
  451. return False
  452. cmd = list(self.make_cmd)
  453. cmd.append(defconfig)
  454. self.ps = subprocess.Popen(cmd, stdout=self.devnull)
  455. self.defconfig = defconfig
  456. self.state = STATE_DEFCONFIG
  457. return True
  458. def poll(self):
  459. """Check the status of the subprocess and handle it as needed.
  460. Returns True if the slot is vacant (i.e. in idle state).
  461. If the configuration is successfully finished, assign a new
  462. subprocess to build include/autoconf.mk.
  463. If include/autoconf.mk is generated, invoke the parser to
  464. parse the .config and the include/autoconf.mk, and then set the
  465. slot back to the idle state.
  466. Returns:
  467. Return True if the subprocess is terminated, False otherwise
  468. """
  469. if self.state == STATE_IDLE:
  470. return True
  471. if self.ps.poll() == None:
  472. return False
  473. if self.ps.poll() != 0:
  474. print >> sys.stderr, log_msg(self.options.color,
  475. COLOR_LIGHT_RED,
  476. self.defconfig,
  477. "failed to process.")
  478. if self.options.exit_on_error:
  479. sys.exit("Exit on error.")
  480. else:
  481. # If --exit-on-error flag is not set,
  482. # skip this board and continue.
  483. # Record the failed board.
  484. self.failed_boards.append(self.defconfig)
  485. self.state = STATE_IDLE
  486. return True
  487. if self.state == STATE_AUTOCONF:
  488. self.parser.update_defconfig(self.defconfig)
  489. """Save off the defconfig in a consistent way"""
  490. cmd = list(self.make_cmd)
  491. cmd.append('savedefconfig')
  492. self.ps = subprocess.Popen(cmd, stdout=self.devnull,
  493. stderr=self.devnull)
  494. self.state = STATE_SAVEDEFCONFIG
  495. return False
  496. if self.state == STATE_SAVEDEFCONFIG:
  497. defconfig_path = os.path.join(self.build_dir, 'defconfig')
  498. shutil.move(defconfig_path,
  499. os.path.join('configs', self.defconfig))
  500. self.state = STATE_IDLE
  501. return True
  502. cross_compile = self.parser.get_cross_compile()
  503. cmd = list(self.make_cmd)
  504. if cross_compile:
  505. cmd.append('CROSS_COMPILE=%s' % cross_compile)
  506. cmd.append('KCONFIG_IGNORE_DUPLICATES=1')
  507. cmd.append('include/config/auto.conf')
  508. self.ps = subprocess.Popen(cmd, stdout=self.devnull)
  509. self.state = STATE_AUTOCONF
  510. return False
  511. def get_failed_boards(self):
  512. """Returns a list of failed boards (defconfigs) in this slot.
  513. """
  514. return self.failed_boards
  515. class Slots:
  516. """Controller of the array of subprocess slots."""
  517. def __init__(self, config_attrs, options):
  518. """Create a new slots controller.
  519. Arguments:
  520. config_attrs: A list of dictionaris containing the name, the type,
  521. and the default value of the target CONFIG.
  522. options: option flags.
  523. """
  524. self.options = options
  525. self.slots = []
  526. devnull = get_devnull()
  527. make_cmd = get_make_cmd()
  528. for i in range(options.jobs):
  529. self.slots.append(Slot(config_attrs, options, devnull, make_cmd))
  530. def add(self, defconfig):
  531. """Add a new subprocess if a vacant slot is found.
  532. Arguments:
  533. defconfig: defconfig name to be put into.
  534. Returns:
  535. Return True on success or False on failure
  536. """
  537. for slot in self.slots:
  538. if slot.add(defconfig):
  539. return True
  540. return False
  541. def available(self):
  542. """Check if there is a vacant slot.
  543. Returns:
  544. Return True if at lease one vacant slot is found, False otherwise.
  545. """
  546. for slot in self.slots:
  547. if slot.poll():
  548. return True
  549. return False
  550. def empty(self):
  551. """Check if all slots are vacant.
  552. Returns:
  553. Return True if all the slots are vacant, False otherwise.
  554. """
  555. ret = True
  556. for slot in self.slots:
  557. if not slot.poll():
  558. ret = False
  559. return ret
  560. def show_failed_boards(self):
  561. """Display all of the failed boards (defconfigs)."""
  562. failed_boards = []
  563. for slot in self.slots:
  564. failed_boards += slot.get_failed_boards()
  565. if len(failed_boards) > 0:
  566. msg = [ "The following boards were not processed due to error:" ]
  567. msg += failed_boards
  568. for line in msg:
  569. print >> sys.stderr, color_text(self.options.color,
  570. COLOR_LIGHT_RED, line)
  571. with open('moveconfig.failed', 'w') as f:
  572. for board in failed_boards:
  573. f.write(board + '\n')
  574. def move_config(config_attrs, options):
  575. """Move config options to defconfig files.
  576. Arguments:
  577. config_attrs: A list of dictionaris, each of them includes the name,
  578. the type, and the default value of the target config.
  579. options: option flags
  580. """
  581. if len(config_attrs) == 0:
  582. print 'Nothing to do. exit.'
  583. sys.exit(0)
  584. print 'Move the following CONFIG options (jobs: %d)' % options.jobs
  585. for config_attr in config_attrs:
  586. print ' %s (type: %s, default: %s)' % (config_attr['config'],
  587. config_attr['type'],
  588. config_attr['default'])
  589. if options.defconfigs:
  590. defconfigs = [line.strip() for line in open(options.defconfigs)]
  591. for i, defconfig in enumerate(defconfigs):
  592. if not defconfig.endswith('_defconfig'):
  593. defconfigs[i] = defconfig + '_defconfig'
  594. if not os.path.exists(os.path.join('configs', defconfigs[i])):
  595. sys.exit('%s - defconfig does not exist. Stopping.' %
  596. defconfigs[i])
  597. else:
  598. # All the defconfig files to be processed
  599. defconfigs = []
  600. for (dirpath, dirnames, filenames) in os.walk('configs'):
  601. dirpath = dirpath[len('configs') + 1:]
  602. for filename in fnmatch.filter(filenames, '*_defconfig'):
  603. defconfigs.append(os.path.join(dirpath, filename))
  604. slots = Slots(config_attrs, options)
  605. # Main loop to process defconfig files:
  606. # Add a new subprocess into a vacant slot.
  607. # Sleep if there is no available slot.
  608. for defconfig in defconfigs:
  609. while not slots.add(defconfig):
  610. while not slots.available():
  611. # No available slot: sleep for a while
  612. time.sleep(SLEEP_TIME)
  613. # wait until all the subprocesses finish
  614. while not slots.empty():
  615. time.sleep(SLEEP_TIME)
  616. slots.show_failed_boards()
  617. def bad_recipe(filename, linenum, msg):
  618. """Print error message with the file name and the line number and exit."""
  619. sys.exit("%s: line %d: error : " % (filename, linenum) + msg)
  620. def parse_recipe(filename):
  621. """Parse the recipe file and retrieve the config attributes.
  622. This function parses the given recipe file and gets the name,
  623. the type, and the default value of the target config options.
  624. Arguments:
  625. filename: path to file to be parsed.
  626. Returns:
  627. A list of dictionaris, each of them includes the name,
  628. the type, and the default value of the target config.
  629. """
  630. config_attrs = []
  631. linenum = 1
  632. for line in open(filename):
  633. tokens = line.split()
  634. if len(tokens) != 3:
  635. bad_recipe(filename, linenum,
  636. "%d fields in this line. Each line must contain 3 fields"
  637. % len(tokens))
  638. (config, type, default) = tokens
  639. # prefix the option name with CONFIG_ if missing
  640. if not config.startswith('CONFIG_'):
  641. config = 'CONFIG_' + config
  642. # sanity check of default values
  643. if type == 'bool':
  644. if not default in ('y', 'n'):
  645. bad_recipe(filename, linenum,
  646. "default for bool type must be either y or n")
  647. elif type == 'tristate':
  648. if not default in ('y', 'm', 'n'):
  649. bad_recipe(filename, linenum,
  650. "default for tristate type must be y, m, or n")
  651. elif type == 'string':
  652. if default[0] != '"' or default[-1] != '"':
  653. bad_recipe(filename, linenum,
  654. "default for string type must be surrounded by double-quotations")
  655. elif type == 'int':
  656. try:
  657. int(default)
  658. except:
  659. bad_recipe(filename, linenum,
  660. "type is int, but default value is not decimal")
  661. elif type == 'hex':
  662. if len(default) < 2 or default[:2] != '0x':
  663. bad_recipe(filename, linenum,
  664. "default for hex type must be prefixed with 0x")
  665. try:
  666. int(default, 16)
  667. except:
  668. bad_recipe(filename, linenum,
  669. "type is hex, but default value is not hexadecimal")
  670. else:
  671. bad_recipe(filename, linenum,
  672. "unsupported type '%s'. type must be one of bool, tristate, string, int, hex"
  673. % type)
  674. config_attrs.append({'config': config, 'type': type, 'default': default})
  675. linenum += 1
  676. return config_attrs
  677. def main():
  678. try:
  679. cpu_count = multiprocessing.cpu_count()
  680. except NotImplementedError:
  681. cpu_count = 1
  682. parser = optparse.OptionParser()
  683. # Add options here
  684. parser.add_option('-c', '--color', action='store_true', default=False,
  685. help='display the log in color')
  686. parser.add_option('-d', '--defconfigs', type='string',
  687. help='a file containing a list of defconfigs to move')
  688. parser.add_option('-n', '--dry-run', action='store_true', default=False,
  689. help='perform a trial run (show log with no changes)')
  690. parser.add_option('-e', '--exit-on-error', action='store_true',
  691. default=False,
  692. help='exit immediately on any error')
  693. parser.add_option('-H', '--headers-only', dest='cleanup_headers_only',
  694. action='store_true', default=False,
  695. help='only cleanup the headers')
  696. parser.add_option('-j', '--jobs', type='int', default=cpu_count,
  697. help='the number of jobs to run simultaneously')
  698. parser.usage += ' recipe_file\n\n' + \
  699. 'The recipe_file should describe config options you want to move.\n' + \
  700. 'Each line should contain config_name, type, default_value\n\n' + \
  701. 'Example:\n' + \
  702. 'CONFIG_FOO bool n\n' + \
  703. 'CONFIG_BAR int 100\n' + \
  704. 'CONFIG_BAZ string "hello"\n'
  705. (options, args) = parser.parse_args()
  706. if len(args) != 1:
  707. parser.print_usage()
  708. sys.exit(1)
  709. config_attrs = parse_recipe(args[0])
  710. update_cross_compile()
  711. check_top_directory()
  712. if not options.cleanup_headers_only:
  713. move_config(config_attrs, options)
  714. cleanup_headers(config_attrs, options.dry_run)
  715. if __name__ == '__main__':
  716. main()