moveconfig.py 38 KB

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