moveconfig.py 31 KB

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