moveconfig.py 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054
  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. First, you must edit the Kconfig to add the menu entries for the configs
  15. you are moving.
  16. And then run this tool giving CONFIG names you want to move.
  17. For example, if you want to move CONFIG_CMD_USB and CONFIG_SYS_TEXT_BASE,
  18. simply type as follows:
  19. $ tools/moveconfig.py CONFIG_CMD_USB CONFIG_SYS_TEXT_BASE
  20. The tool walks through all the defconfig files and move the given CONFIGs.
  21. The log is also displayed on the terminal.
  22. The log is printed for each defconfig as follows:
  23. <defconfig_name>
  24. <action1>
  25. <action2>
  26. <action3>
  27. ...
  28. <defconfig_name> is the name of the defconfig.
  29. <action*> shows what the tool did for that defconfig.
  30. It looks like one of the followings:
  31. - Move 'CONFIG_... '
  32. This config option was moved to the defconfig
  33. - CONFIG_... is not defined in Kconfig. Do nothing.
  34. The entry for this CONFIG was not found in Kconfig.
  35. There are two common cases:
  36. - You forgot to create an entry for the CONFIG before running
  37. this tool, or made a typo in a CONFIG passed to this tool.
  38. - The entry was hidden due to unmet 'depends on'.
  39. This is correct behavior.
  40. - 'CONFIG_...' is the same as the define in Kconfig. Do nothing.
  41. The define in the config header matched the one in Kconfig.
  42. We do not need to touch it.
  43. - Undefined. Do nothing.
  44. This config option was not found in the config header.
  45. Nothing to do.
  46. - Compiler is missing. Do nothing.
  47. The compiler specified for this architecture was not found
  48. in your PATH environment.
  49. (If -e option is passed, the tool exits immediately.)
  50. - Failed to process.
  51. An error occurred during processing this defconfig. Skipped.
  52. (If -e option is passed, the tool exits immediately on error.)
  53. Finally, you will be asked, Clean up headers? [y/n]:
  54. If you say 'y' here, the unnecessary config defines are removed
  55. from the config headers (include/configs/*.h).
  56. It just uses the regex method, so you should not rely on it.
  57. Just in case, please do 'git diff' to see what happened.
  58. How does it work?
  59. -----------------
  60. This tool runs configuration and builds include/autoconf.mk for every
  61. defconfig. The config options defined in Kconfig appear in the .config
  62. file (unless they are hidden because of unmet dependency.)
  63. On the other hand, the config options defined by board headers are seen
  64. in include/autoconf.mk. The tool looks for the specified options in both
  65. of them to decide the appropriate action for the options. If the given
  66. config option is found in the .config, but its value does not match the
  67. one from the board header, the config option in the .config is replaced
  68. with the define in the board header. Then, the .config is synced by
  69. "make savedefconfig" and the defconfig is updated with it.
  70. For faster processing, this tool handles multi-threading. It creates
  71. separate build directories where the out-of-tree build is run. The
  72. temporary build directories are automatically created and deleted as
  73. needed. The number of threads are chosen based on the number of the CPU
  74. cores of your system although you can change it via -j (--jobs) option.
  75. Toolchains
  76. ----------
  77. Appropriate toolchain are necessary to generate include/autoconf.mk
  78. for all the architectures supported by U-Boot. Most of them are available
  79. at the kernel.org site, some are not provided by kernel.org.
  80. The default per-arch CROSS_COMPILE used by this tool is specified by
  81. the list below, CROSS_COMPILE. You may wish to update the list to
  82. use your own. Instead of modifying the list directly, you can give
  83. them via environments.
  84. Available options
  85. -----------------
  86. -c, --color
  87. Surround each portion of the log with escape sequences to display it
  88. in color on the terminal.
  89. -d, --defconfigs
  90. Specify a file containing a list of defconfigs to move
  91. -n, --dry-run
  92. Perform a trial run that does not make any changes. It is useful to
  93. see what is going to happen before one actually runs it.
  94. -e, --exit-on-error
  95. Exit immediately if Make exits with a non-zero status while processing
  96. a defconfig file.
  97. -s, --force-sync
  98. Do "make savedefconfig" forcibly for all the defconfig files.
  99. If not specified, "make savedefconfig" only occurs for cases
  100. where at least one CONFIG was moved.
  101. -H, --headers-only
  102. Only cleanup the headers; skip the defconfig processing
  103. -j, --jobs
  104. Specify the number of threads to run simultaneously. If not specified,
  105. the number of threads is the same as the number of CPU cores.
  106. -r, --git-ref
  107. Specify the git ref to clone for building the autoconf.mk. If unspecified
  108. use the CWD. This is useful for when changes to the Kconfig affect the
  109. default values and you want to capture the state of the defconfig from
  110. before that change was in effect. If in doubt, specify a ref pre-Kconfig
  111. changes (use HEAD if Kconfig changes are not committed). Worst case it will
  112. take a bit longer to run, but will always do the right thing.
  113. -v, --verbose
  114. Show any build errors as boards are built
  115. To see the complete list of supported options, run
  116. $ tools/moveconfig.py -h
  117. """
  118. import filecmp
  119. import fnmatch
  120. import multiprocessing
  121. import optparse
  122. import os
  123. import re
  124. import shutil
  125. import subprocess
  126. import sys
  127. import tempfile
  128. import time
  129. SHOW_GNU_MAKE = 'scripts/show-gnu-make'
  130. SLEEP_TIME=0.03
  131. # Here is the list of cross-tools I use.
  132. # Most of them are available at kernel.org
  133. # (https://www.kernel.org/pub/tools/crosstool/files/bin/), except the followings:
  134. # arc: https://github.com/foss-for-synopsys-dwc-arc-processors/toolchain/releases
  135. # blackfin: http://sourceforge.net/projects/adi-toolchain/files/
  136. # nds32: http://osdk.andestech.com/packages/nds32le-linux-glibc-v1.tgz
  137. # nios2: https://sourcery.mentor.com/GNUToolchain/subscription42545
  138. # sh: http://sourcery.mentor.com/public/gnu_toolchain/sh-linux-gnu
  139. #
  140. # openrisc kernel.org toolchain is out of date, download latest one from
  141. # http://opencores.org/or1k/OpenRISC_GNU_tool_chain#Prebuilt_versions
  142. CROSS_COMPILE = {
  143. 'arc': 'arc-linux-',
  144. 'aarch64': 'aarch64-linux-',
  145. 'arm': 'arm-unknown-linux-gnueabi-',
  146. 'avr32': 'avr32-linux-',
  147. 'blackfin': 'bfin-elf-',
  148. 'm68k': 'm68k-linux-',
  149. 'microblaze': 'microblaze-linux-',
  150. 'mips': 'mips-linux-',
  151. 'nds32': 'nds32le-linux-',
  152. 'nios2': 'nios2-linux-gnu-',
  153. 'openrisc': 'or1k-elf-',
  154. 'powerpc': 'powerpc-linux-',
  155. 'sh': 'sh-linux-gnu-',
  156. 'sparc': 'sparc-linux-',
  157. 'x86': 'i386-linux-'
  158. }
  159. STATE_IDLE = 0
  160. STATE_DEFCONFIG = 1
  161. STATE_AUTOCONF = 2
  162. STATE_SAVEDEFCONFIG = 3
  163. ACTION_MOVE = 0
  164. ACTION_NO_ENTRY = 1
  165. ACTION_NO_CHANGE = 2
  166. COLOR_BLACK = '0;30'
  167. COLOR_RED = '0;31'
  168. COLOR_GREEN = '0;32'
  169. COLOR_BROWN = '0;33'
  170. COLOR_BLUE = '0;34'
  171. COLOR_PURPLE = '0;35'
  172. COLOR_CYAN = '0;36'
  173. COLOR_LIGHT_GRAY = '0;37'
  174. COLOR_DARK_GRAY = '1;30'
  175. COLOR_LIGHT_RED = '1;31'
  176. COLOR_LIGHT_GREEN = '1;32'
  177. COLOR_YELLOW = '1;33'
  178. COLOR_LIGHT_BLUE = '1;34'
  179. COLOR_LIGHT_PURPLE = '1;35'
  180. COLOR_LIGHT_CYAN = '1;36'
  181. COLOR_WHITE = '1;37'
  182. ### helper functions ###
  183. def get_devnull():
  184. """Get the file object of '/dev/null' device."""
  185. try:
  186. devnull = subprocess.DEVNULL # py3k
  187. except AttributeError:
  188. devnull = open(os.devnull, 'wb')
  189. return devnull
  190. def check_top_directory():
  191. """Exit if we are not at the top of source directory."""
  192. for f in ('README', 'Licenses'):
  193. if not os.path.exists(f):
  194. sys.exit('Please run at the top of source directory.')
  195. def check_clean_directory():
  196. """Exit if the source tree is not clean."""
  197. for f in ('.config', 'include/config'):
  198. if os.path.exists(f):
  199. sys.exit("source tree is not clean, please run 'make mrproper'")
  200. def get_make_cmd():
  201. """Get the command name of GNU Make.
  202. U-Boot needs GNU Make for building, but the command name is not
  203. necessarily "make". (for example, "gmake" on FreeBSD).
  204. Returns the most appropriate command name on your system.
  205. """
  206. process = subprocess.Popen([SHOW_GNU_MAKE], stdout=subprocess.PIPE)
  207. ret = process.communicate()
  208. if process.returncode:
  209. sys.exit('GNU Make not found')
  210. return ret[0].rstrip()
  211. def color_text(color_enabled, color, string):
  212. """Return colored string."""
  213. if color_enabled:
  214. # LF should not be surrounded by the escape sequence.
  215. # Otherwise, additional whitespace or line-feed might be printed.
  216. return '\n'.join([ '\033[' + color + 'm' + s + '\033[0m' if s else ''
  217. for s in string.split('\n') ])
  218. else:
  219. return string
  220. def update_cross_compile(color_enabled):
  221. """Update per-arch CROSS_COMPILE via environment variables
  222. The default CROSS_COMPILE values are available
  223. in the CROSS_COMPILE list above.
  224. You can override them via environment variables
  225. CROSS_COMPILE_{ARCH}.
  226. For example, if you want to override toolchain prefixes
  227. for ARM and PowerPC, you can do as follows in your shell:
  228. export CROSS_COMPILE_ARM=...
  229. export CROSS_COMPILE_POWERPC=...
  230. Then, this function checks if specified compilers really exist in your
  231. PATH environment.
  232. """
  233. archs = []
  234. for arch in os.listdir('arch'):
  235. if os.path.exists(os.path.join('arch', arch, 'Makefile')):
  236. archs.append(arch)
  237. # arm64 is a special case
  238. archs.append('aarch64')
  239. for arch in archs:
  240. env = 'CROSS_COMPILE_' + arch.upper()
  241. cross_compile = os.environ.get(env)
  242. if not cross_compile:
  243. cross_compile = CROSS_COMPILE.get(arch, '')
  244. for path in os.environ["PATH"].split(os.pathsep):
  245. gcc_path = os.path.join(path, cross_compile + 'gcc')
  246. if os.path.isfile(gcc_path) and os.access(gcc_path, os.X_OK):
  247. break
  248. else:
  249. print >> sys.stderr, color_text(color_enabled, COLOR_YELLOW,
  250. 'warning: %sgcc: not found in PATH. %s architecture boards will be skipped'
  251. % (cross_compile, arch))
  252. cross_compile = None
  253. CROSS_COMPILE[arch] = cross_compile
  254. def cleanup_one_header(header_path, patterns, dry_run):
  255. """Clean regex-matched lines away from a file.
  256. Arguments:
  257. header_path: path to the cleaned file.
  258. patterns: list of regex patterns. Any lines matching to these
  259. patterns are deleted.
  260. dry_run: make no changes, but still display log.
  261. """
  262. with open(header_path) as f:
  263. lines = f.readlines()
  264. matched = []
  265. for i, line in enumerate(lines):
  266. for pattern in patterns:
  267. m = pattern.search(line)
  268. if m:
  269. print '%s: %s: %s' % (header_path, i + 1, line),
  270. matched.append(i)
  271. break
  272. if dry_run or not matched:
  273. return
  274. with open(header_path, 'w') as f:
  275. for i, line in enumerate(lines):
  276. if not i in matched:
  277. f.write(line)
  278. def cleanup_headers(configs, dry_run):
  279. """Delete config defines from board headers.
  280. Arguments:
  281. configs: A list of CONFIGs to remove.
  282. dry_run: make no changes, but still display log.
  283. """
  284. while True:
  285. choice = raw_input('Clean up headers? [y/n]: ').lower()
  286. print choice
  287. if choice == 'y' or choice == 'n':
  288. break
  289. if choice == 'n':
  290. return
  291. patterns = []
  292. for config in configs:
  293. patterns.append(re.compile(r'#\s*define\s+%s\W' % config))
  294. patterns.append(re.compile(r'#\s*undef\s+%s\W' % config))
  295. for dir in 'include', 'arch', 'board':
  296. for (dirpath, dirnames, filenames) in os.walk(dir):
  297. for filename in filenames:
  298. if not fnmatch.fnmatch(filename, '*~'):
  299. cleanup_one_header(os.path.join(dirpath, filename),
  300. patterns, dry_run)
  301. ### classes ###
  302. class Progress:
  303. """Progress Indicator"""
  304. def __init__(self, total):
  305. """Create a new progress indicator.
  306. Arguments:
  307. total: A number of defconfig files to process.
  308. """
  309. self.current = 0
  310. self.total = total
  311. def inc(self):
  312. """Increment the number of processed defconfig files."""
  313. self.current += 1
  314. def show(self):
  315. """Display the progress."""
  316. print ' %d defconfigs out of %d\r' % (self.current, self.total),
  317. sys.stdout.flush()
  318. class KconfigParser:
  319. """A parser of .config and include/autoconf.mk."""
  320. re_arch = re.compile(r'CONFIG_SYS_ARCH="(.*)"')
  321. re_cpu = re.compile(r'CONFIG_SYS_CPU="(.*)"')
  322. def __init__(self, configs, options, build_dir):
  323. """Create a new parser.
  324. Arguments:
  325. configs: A list of CONFIGs to move.
  326. options: option flags.
  327. build_dir: Build directory.
  328. """
  329. self.configs = configs
  330. self.options = options
  331. self.dotconfig = os.path.join(build_dir, '.config')
  332. self.autoconf = os.path.join(build_dir, 'include', 'autoconf.mk')
  333. self.config_autoconf = os.path.join(build_dir, 'include', 'config',
  334. 'auto.conf')
  335. self.defconfig = os.path.join(build_dir, 'defconfig')
  336. def get_cross_compile(self):
  337. """Parse .config file and return CROSS_COMPILE.
  338. Returns:
  339. A string storing the compiler prefix for the architecture.
  340. Return a NULL string for architectures that do not require
  341. compiler prefix (Sandbox and native build is the case).
  342. Return None if the specified compiler is missing in your PATH.
  343. Caller should distinguish '' and None.
  344. """
  345. arch = ''
  346. cpu = ''
  347. for line in open(self.dotconfig):
  348. m = self.re_arch.match(line)
  349. if m:
  350. arch = m.group(1)
  351. continue
  352. m = self.re_cpu.match(line)
  353. if m:
  354. cpu = m.group(1)
  355. if not arch:
  356. return None
  357. # fix-up for aarch64
  358. if arch == 'arm' and cpu == 'armv8':
  359. arch = 'aarch64'
  360. return CROSS_COMPILE.get(arch, None)
  361. def parse_one_config(self, config, dotconfig_lines, autoconf_lines):
  362. """Parse .config, defconfig, include/autoconf.mk for one config.
  363. This function looks for the config options in the lines from
  364. defconfig, .config, and include/autoconf.mk in order to decide
  365. which action should be taken for this defconfig.
  366. Arguments:
  367. config: CONFIG name to parse.
  368. dotconfig_lines: lines from the .config file.
  369. autoconf_lines: lines from the include/autoconf.mk file.
  370. Returns:
  371. A tupple of the action for this defconfig and the line
  372. matched for the config.
  373. """
  374. not_set = '# %s is not set' % config
  375. for line in dotconfig_lines:
  376. line = line.rstrip()
  377. if line.startswith(config + '=') or line == not_set:
  378. old_val = line
  379. break
  380. else:
  381. return (ACTION_NO_ENTRY, config)
  382. for line in autoconf_lines:
  383. line = line.rstrip()
  384. if line.startswith(config + '='):
  385. new_val = line
  386. break
  387. else:
  388. new_val = not_set
  389. # If this CONFIG is neither bool nor trisate
  390. if old_val[-2:] != '=y' and old_val[-2:] != '=m' and old_val != not_set:
  391. # tools/scripts/define2mk.sed changes '1' to 'y'.
  392. # This is a problem if the CONFIG is int type.
  393. # Check the type in Kconfig and handle it correctly.
  394. if new_val[-2:] == '=y':
  395. new_val = new_val[:-1] + '1'
  396. return (ACTION_NO_CHANGE if old_val == new_val else ACTION_MOVE,
  397. new_val)
  398. def update_dotconfig(self):
  399. """Parse files for the config options and update the .config.
  400. This function parses the generated .config and include/autoconf.mk
  401. searching the target options.
  402. Move the config option(s) to the .config as needed.
  403. Arguments:
  404. defconfig: defconfig name.
  405. Returns:
  406. Return a tuple of (updated flag, log string).
  407. The "updated flag" is True if the .config was updated, False
  408. otherwise. The "log string" shows what happend to the .config.
  409. """
  410. results = []
  411. updated = False
  412. with open(self.dotconfig) as f:
  413. dotconfig_lines = f.readlines()
  414. with open(self.autoconf) as f:
  415. autoconf_lines = f.readlines()
  416. for config in self.configs:
  417. result = self.parse_one_config(config, dotconfig_lines,
  418. autoconf_lines)
  419. results.append(result)
  420. log = ''
  421. for (action, value) in results:
  422. if action == ACTION_MOVE:
  423. actlog = "Move '%s'" % value
  424. log_color = COLOR_LIGHT_GREEN
  425. elif action == ACTION_NO_ENTRY:
  426. actlog = "%s is not defined in Kconfig. Do nothing." % value
  427. log_color = COLOR_LIGHT_BLUE
  428. elif action == ACTION_NO_CHANGE:
  429. actlog = "'%s' is the same as the define in Kconfig. Do nothing." \
  430. % value
  431. log_color = COLOR_LIGHT_PURPLE
  432. else:
  433. sys.exit("Internal Error. This should not happen.")
  434. log += color_text(self.options.color, log_color, actlog) + '\n'
  435. with open(self.dotconfig, 'a') as f:
  436. for (action, value) in results:
  437. if action == ACTION_MOVE:
  438. f.write(value + '\n')
  439. updated = True
  440. self.results = results
  441. os.remove(self.config_autoconf)
  442. os.remove(self.autoconf)
  443. return (updated, log)
  444. def check_defconfig(self):
  445. """Check the defconfig after savedefconfig
  446. Returns:
  447. Return additional log if moved CONFIGs were removed again by
  448. 'make savedefconfig'.
  449. """
  450. log = ''
  451. with open(self.defconfig) as f:
  452. defconfig_lines = f.readlines()
  453. for (action, value) in self.results:
  454. if action != ACTION_MOVE:
  455. continue
  456. if not value + '\n' in defconfig_lines:
  457. log += color_text(self.options.color, COLOR_YELLOW,
  458. "'%s' was removed by savedefconfig.\n" %
  459. value)
  460. return log
  461. class Slot:
  462. """A slot to store a subprocess.
  463. Each instance of this class handles one subprocess.
  464. This class is useful to control multiple threads
  465. for faster processing.
  466. """
  467. def __init__(self, configs, options, progress, devnull, make_cmd, reference_src_dir):
  468. """Create a new process slot.
  469. Arguments:
  470. configs: A list of CONFIGs to move.
  471. options: option flags.
  472. progress: A progress indicator.
  473. devnull: A file object of '/dev/null'.
  474. make_cmd: command name of GNU Make.
  475. reference_src_dir: Determine the true starting config state from this
  476. source tree.
  477. """
  478. self.options = options
  479. self.progress = progress
  480. self.build_dir = tempfile.mkdtemp()
  481. self.devnull = devnull
  482. self.make_cmd = (make_cmd, 'O=' + self.build_dir)
  483. self.reference_src_dir = reference_src_dir
  484. self.parser = KconfigParser(configs, options, self.build_dir)
  485. self.state = STATE_IDLE
  486. self.failed_boards = []
  487. self.suspicious_boards = []
  488. def __del__(self):
  489. """Delete the working directory
  490. This function makes sure the temporary directory is cleaned away
  491. even if Python suddenly dies due to error. It should be done in here
  492. because it is guaranteed the destructor is always invoked when the
  493. instance of the class gets unreferenced.
  494. If the subprocess is still running, wait until it finishes.
  495. """
  496. if self.state != STATE_IDLE:
  497. while self.ps.poll() == None:
  498. pass
  499. shutil.rmtree(self.build_dir)
  500. def add(self, defconfig):
  501. """Assign a new subprocess for defconfig and add it to the slot.
  502. If the slot is vacant, create a new subprocess for processing the
  503. given defconfig and add it to the slot. Just returns False if
  504. the slot is occupied (i.e. the current subprocess is still running).
  505. Arguments:
  506. defconfig: defconfig name.
  507. Returns:
  508. Return True on success or False on failure
  509. """
  510. if self.state != STATE_IDLE:
  511. return False
  512. self.defconfig = defconfig
  513. self.log = ''
  514. self.current_src_dir = self.reference_src_dir
  515. self.do_defconfig()
  516. return True
  517. def poll(self):
  518. """Check the status of the subprocess and handle it as needed.
  519. Returns True if the slot is vacant (i.e. in idle state).
  520. If the configuration is successfully finished, assign a new
  521. subprocess to build include/autoconf.mk.
  522. If include/autoconf.mk is generated, invoke the parser to
  523. parse the .config and the include/autoconf.mk, moving
  524. config options to the .config as needed.
  525. If the .config was updated, run "make savedefconfig" to sync
  526. it, update the original defconfig, and then set the slot back
  527. to the idle state.
  528. Returns:
  529. Return True if the subprocess is terminated, False otherwise
  530. """
  531. if self.state == STATE_IDLE:
  532. return True
  533. if self.ps.poll() == None:
  534. return False
  535. if self.ps.poll() != 0:
  536. self.handle_error()
  537. elif self.state == STATE_DEFCONFIG:
  538. if self.reference_src_dir and not self.current_src_dir:
  539. self.do_savedefconfig()
  540. else:
  541. self.do_autoconf()
  542. elif self.state == STATE_AUTOCONF:
  543. if self.current_src_dir:
  544. self.current_src_dir = None
  545. self.do_defconfig()
  546. else:
  547. self.do_savedefconfig()
  548. elif self.state == STATE_SAVEDEFCONFIG:
  549. self.update_defconfig()
  550. else:
  551. sys.exit("Internal Error. This should not happen.")
  552. return True if self.state == STATE_IDLE else False
  553. def handle_error(self):
  554. """Handle error cases."""
  555. self.log += color_text(self.options.color, COLOR_LIGHT_RED,
  556. "Failed to process.\n")
  557. if self.options.verbose:
  558. self.log += color_text(self.options.color, COLOR_LIGHT_CYAN,
  559. self.ps.stderr.read())
  560. self.finish(False)
  561. def do_defconfig(self):
  562. """Run 'make <board>_defconfig' to create the .config file."""
  563. cmd = list(self.make_cmd)
  564. cmd.append(self.defconfig)
  565. self.ps = subprocess.Popen(cmd, stdout=self.devnull,
  566. stderr=subprocess.PIPE,
  567. cwd=self.current_src_dir)
  568. self.state = STATE_DEFCONFIG
  569. def do_autoconf(self):
  570. """Run 'make include/config/auto.conf'."""
  571. self.cross_compile = self.parser.get_cross_compile()
  572. if self.cross_compile is None:
  573. self.log += color_text(self.options.color, COLOR_YELLOW,
  574. "Compiler is missing. Do nothing.\n")
  575. self.finish(False)
  576. return
  577. cmd = list(self.make_cmd)
  578. if self.cross_compile:
  579. cmd.append('CROSS_COMPILE=%s' % self.cross_compile)
  580. cmd.append('KCONFIG_IGNORE_DUPLICATES=1')
  581. cmd.append('include/config/auto.conf')
  582. self.ps = subprocess.Popen(cmd, stdout=self.devnull,
  583. stderr=subprocess.PIPE,
  584. cwd=self.current_src_dir)
  585. self.state = STATE_AUTOCONF
  586. def do_savedefconfig(self):
  587. """Update the .config and run 'make savedefconfig'."""
  588. (updated, log) = self.parser.update_dotconfig()
  589. self.log += log
  590. if not self.options.force_sync and not updated:
  591. self.finish(True)
  592. return
  593. if updated:
  594. self.log += color_text(self.options.color, COLOR_LIGHT_GREEN,
  595. "Syncing by savedefconfig...\n")
  596. else:
  597. self.log += "Syncing by savedefconfig (forced by option)...\n"
  598. cmd = list(self.make_cmd)
  599. cmd.append('savedefconfig')
  600. self.ps = subprocess.Popen(cmd, stdout=self.devnull,
  601. stderr=subprocess.PIPE)
  602. self.state = STATE_SAVEDEFCONFIG
  603. def update_defconfig(self):
  604. """Update the input defconfig and go back to the idle state."""
  605. log = self.parser.check_defconfig()
  606. if log:
  607. self.suspicious_boards.append(self.defconfig)
  608. self.log += log
  609. orig_defconfig = os.path.join('configs', self.defconfig)
  610. new_defconfig = os.path.join(self.build_dir, 'defconfig')
  611. updated = not filecmp.cmp(orig_defconfig, new_defconfig)
  612. if updated:
  613. self.log += color_text(self.options.color, COLOR_LIGHT_BLUE,
  614. "defconfig was updated.\n")
  615. if not self.options.dry_run and updated:
  616. shutil.move(new_defconfig, orig_defconfig)
  617. self.finish(True)
  618. def finish(self, success):
  619. """Display log along with progress and go to the idle state.
  620. Arguments:
  621. success: Should be True when the defconfig was processed
  622. successfully, or False when it fails.
  623. """
  624. # output at least 30 characters to hide the "* defconfigs out of *".
  625. log = self.defconfig.ljust(30) + '\n'
  626. log += '\n'.join([ ' ' + s for s in self.log.split('\n') ])
  627. # Some threads are running in parallel.
  628. # Print log atomically to not mix up logs from different threads.
  629. print >> (sys.stdout if success else sys.stderr), log
  630. if not success:
  631. if self.options.exit_on_error:
  632. sys.exit("Exit on error.")
  633. # If --exit-on-error flag is not set, skip this board and continue.
  634. # Record the failed board.
  635. self.failed_boards.append(self.defconfig)
  636. self.progress.inc()
  637. self.progress.show()
  638. self.state = STATE_IDLE
  639. def get_failed_boards(self):
  640. """Returns a list of failed boards (defconfigs) in this slot.
  641. """
  642. return self.failed_boards
  643. def get_suspicious_boards(self):
  644. """Returns a list of boards (defconfigs) with possible misconversion.
  645. """
  646. return self.suspicious_boards
  647. class Slots:
  648. """Controller of the array of subprocess slots."""
  649. def __init__(self, configs, options, progress, reference_src_dir):
  650. """Create a new slots controller.
  651. Arguments:
  652. configs: A list of CONFIGs to move.
  653. options: option flags.
  654. progress: A progress indicator.
  655. reference_src_dir: Determine the true starting config state from this
  656. source tree.
  657. """
  658. self.options = options
  659. self.slots = []
  660. devnull = get_devnull()
  661. make_cmd = get_make_cmd()
  662. for i in range(options.jobs):
  663. self.slots.append(Slot(configs, options, progress, devnull,
  664. make_cmd, reference_src_dir))
  665. def add(self, defconfig):
  666. """Add a new subprocess if a vacant slot is found.
  667. Arguments:
  668. defconfig: defconfig name to be put into.
  669. Returns:
  670. Return True on success or False on failure
  671. """
  672. for slot in self.slots:
  673. if slot.add(defconfig):
  674. return True
  675. return False
  676. def available(self):
  677. """Check if there is a vacant slot.
  678. Returns:
  679. Return True if at lease one vacant slot is found, False otherwise.
  680. """
  681. for slot in self.slots:
  682. if slot.poll():
  683. return True
  684. return False
  685. def empty(self):
  686. """Check if all slots are vacant.
  687. Returns:
  688. Return True if all the slots are vacant, False otherwise.
  689. """
  690. ret = True
  691. for slot in self.slots:
  692. if not slot.poll():
  693. ret = False
  694. return ret
  695. def show_failed_boards(self):
  696. """Display all of the failed boards (defconfigs)."""
  697. boards = []
  698. output_file = 'moveconfig.failed'
  699. for slot in self.slots:
  700. boards += slot.get_failed_boards()
  701. if boards:
  702. boards = '\n'.join(boards) + '\n'
  703. msg = "The following boards were not processed due to error:\n"
  704. msg += boards
  705. msg += "(the list has been saved in %s)\n" % output_file
  706. print >> sys.stderr, color_text(self.options.color, COLOR_LIGHT_RED,
  707. msg)
  708. with open(output_file, 'w') as f:
  709. f.write(boards)
  710. def show_suspicious_boards(self):
  711. """Display all boards (defconfigs) with possible misconversion."""
  712. boards = []
  713. output_file = 'moveconfig.suspicious'
  714. for slot in self.slots:
  715. boards += slot.get_suspicious_boards()
  716. if boards:
  717. boards = '\n'.join(boards) + '\n'
  718. msg = "The following boards might have been converted incorrectly.\n"
  719. msg += "It is highly recommended to check them manually:\n"
  720. msg += boards
  721. msg += "(the list has been saved in %s)\n" % output_file
  722. print >> sys.stderr, color_text(self.options.color, COLOR_YELLOW,
  723. msg)
  724. with open(output_file, 'w') as f:
  725. f.write(boards)
  726. class ReferenceSource:
  727. """Reference source against which original configs should be parsed."""
  728. def __init__(self, commit):
  729. """Create a reference source directory based on a specified commit.
  730. Arguments:
  731. commit: commit to git-clone
  732. """
  733. self.src_dir = tempfile.mkdtemp()
  734. print "Cloning git repo to a separate work directory..."
  735. subprocess.check_output(['git', 'clone', os.getcwd(), '.'],
  736. cwd=self.src_dir)
  737. print "Checkout '%s' to build the original autoconf.mk." % \
  738. subprocess.check_output(['git', 'rev-parse', '--short', commit]).strip()
  739. subprocess.check_output(['git', 'checkout', commit],
  740. stderr=subprocess.STDOUT, cwd=self.src_dir)
  741. def __del__(self):
  742. """Delete the reference source directory
  743. This function makes sure the temporary directory is cleaned away
  744. even if Python suddenly dies due to error. It should be done in here
  745. because it is guaranteed the destructor is always invoked when the
  746. instance of the class gets unreferenced.
  747. """
  748. shutil.rmtree(self.src_dir)
  749. def get_dir(self):
  750. """Return the absolute path to the reference source directory."""
  751. return self.src_dir
  752. def move_config(configs, options):
  753. """Move config options to defconfig files.
  754. Arguments:
  755. configs: A list of CONFIGs to move.
  756. options: option flags
  757. """
  758. if len(configs) == 0:
  759. if options.force_sync:
  760. print 'No CONFIG is specified. You are probably syncing defconfigs.',
  761. else:
  762. print 'Neither CONFIG nor --force-sync is specified. Nothing will happen.',
  763. else:
  764. print 'Move ' + ', '.join(configs),
  765. print '(jobs: %d)\n' % options.jobs
  766. if options.git_ref:
  767. reference_src = ReferenceSource(options.git_ref)
  768. reference_src_dir = reference_src.get_dir()
  769. else:
  770. reference_src_dir = None
  771. if options.defconfigs:
  772. defconfigs = [line.strip() for line in open(options.defconfigs)]
  773. for i, defconfig in enumerate(defconfigs):
  774. if not defconfig.endswith('_defconfig'):
  775. defconfigs[i] = defconfig + '_defconfig'
  776. if not os.path.exists(os.path.join('configs', defconfigs[i])):
  777. sys.exit('%s - defconfig does not exist. Stopping.' %
  778. defconfigs[i])
  779. else:
  780. # All the defconfig files to be processed
  781. defconfigs = []
  782. for (dirpath, dirnames, filenames) in os.walk('configs'):
  783. dirpath = dirpath[len('configs') + 1:]
  784. for filename in fnmatch.filter(filenames, '*_defconfig'):
  785. defconfigs.append(os.path.join(dirpath, filename))
  786. progress = Progress(len(defconfigs))
  787. slots = Slots(configs, options, progress, reference_src_dir)
  788. # Main loop to process defconfig files:
  789. # Add a new subprocess into a vacant slot.
  790. # Sleep if there is no available slot.
  791. for defconfig in defconfigs:
  792. while not slots.add(defconfig):
  793. while not slots.available():
  794. # No available slot: sleep for a while
  795. time.sleep(SLEEP_TIME)
  796. # wait until all the subprocesses finish
  797. while not slots.empty():
  798. time.sleep(SLEEP_TIME)
  799. print ''
  800. slots.show_failed_boards()
  801. slots.show_suspicious_boards()
  802. def main():
  803. try:
  804. cpu_count = multiprocessing.cpu_count()
  805. except NotImplementedError:
  806. cpu_count = 1
  807. parser = optparse.OptionParser()
  808. # Add options here
  809. parser.add_option('-c', '--color', action='store_true', default=False,
  810. help='display the log in color')
  811. parser.add_option('-d', '--defconfigs', type='string',
  812. help='a file containing a list of defconfigs to move')
  813. parser.add_option('-n', '--dry-run', action='store_true', default=False,
  814. help='perform a trial run (show log with no changes)')
  815. parser.add_option('-e', '--exit-on-error', action='store_true',
  816. default=False,
  817. help='exit immediately on any error')
  818. parser.add_option('-s', '--force-sync', action='store_true', default=False,
  819. help='force sync by savedefconfig')
  820. parser.add_option('-H', '--headers-only', dest='cleanup_headers_only',
  821. action='store_true', default=False,
  822. help='only cleanup the headers')
  823. parser.add_option('-j', '--jobs', type='int', default=cpu_count,
  824. help='the number of jobs to run simultaneously')
  825. parser.add_option('-r', '--git-ref', type='string',
  826. help='the git ref to clone for building the autoconf.mk')
  827. parser.add_option('-v', '--verbose', action='store_true', default=False,
  828. help='show any build errors as boards are built')
  829. parser.usage += ' CONFIG ...'
  830. (options, configs) = parser.parse_args()
  831. if len(configs) == 0 and not options.force_sync:
  832. parser.print_usage()
  833. sys.exit(1)
  834. # prefix the option name with CONFIG_ if missing
  835. configs = [ config if config.startswith('CONFIG_') else 'CONFIG_' + config
  836. for config in configs ]
  837. check_top_directory()
  838. check_clean_directory()
  839. update_cross_compile(options.color)
  840. if not options.cleanup_headers_only:
  841. move_config(configs, options)
  842. if configs:
  843. cleanup_headers(configs, options.dry_run)
  844. if __name__ == '__main__':
  845. main()