moveconfig.py 31 KB

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