Fork of the vendor (Boundary Devices) u-boot for Reform 2, with minor tweaks. The goal is to migrate to mainstream u-boot or barebox ASAP. The main impediment so far is the 4GB RAM config.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.
 
 
 
 
 
 

1375 lines
45 KiB

  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 following:
  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. The option is not
  35. defined in the config header, either. So, this case can be just skipped.
  36. - CONFIG_... is not defined in Kconfig (suspicious). Do nothing.
  37. This option is defined in the config header, but its entry was not found
  38. in Kconfig.
  39. There are two common cases:
  40. - You forgot to create an entry for the CONFIG before running
  41. this tool, or made a typo in a CONFIG passed to this tool.
  42. - The entry was hidden due to unmet 'depends on'.
  43. The tool does not know if the result is reasonable, so please check it
  44. manually.
  45. - 'CONFIG_...' is the same as the define in Kconfig. Do nothing.
  46. The define in the config header matched the one in Kconfig.
  47. We do not need to touch it.
  48. - Compiler is missing. Do nothing.
  49. The compiler specified for this architecture was not found
  50. in your PATH environment.
  51. (If -e option is passed, the tool exits immediately.)
  52. - Failed to process.
  53. An error occurred during processing this defconfig. Skipped.
  54. (If -e option is passed, the tool exits immediately on error.)
  55. Finally, you will be asked, Clean up headers? [y/n]:
  56. If you say 'y' here, the unnecessary config defines are removed
  57. from the config headers (include/configs/*.h).
  58. It just uses the regex method, so you should not rely on it.
  59. Just in case, please do 'git diff' to see what happened.
  60. How does it work?
  61. -----------------
  62. This tool runs configuration and builds include/autoconf.mk for every
  63. defconfig. The config options defined in Kconfig appear in the .config
  64. file (unless they are hidden because of unmet dependency.)
  65. On the other hand, the config options defined by board headers are seen
  66. in include/autoconf.mk. The tool looks for the specified options in both
  67. of them to decide the appropriate action for the options. If the given
  68. config option is found in the .config, but its value does not match the
  69. one from the board header, the config option in the .config is replaced
  70. with the define in the board header. Then, the .config is synced by
  71. "make savedefconfig" and the defconfig is updated with it.
  72. For faster processing, this tool handles multi-threading. It creates
  73. separate build directories where the out-of-tree build is run. The
  74. temporary build directories are automatically created and deleted as
  75. needed. The number of threads are chosen based on the number of the CPU
  76. cores of your system although you can change it via -j (--jobs) option.
  77. Toolchains
  78. ----------
  79. Appropriate toolchain are necessary to generate include/autoconf.mk
  80. for all the architectures supported by U-Boot. Most of them are available
  81. at the kernel.org site, some are not provided by kernel.org.
  82. The default per-arch CROSS_COMPILE used by this tool is specified by
  83. the list below, CROSS_COMPILE. You may wish to update the list to
  84. use your own. Instead of modifying the list directly, you can give
  85. them via environments.
  86. Available options
  87. -----------------
  88. -c, --color
  89. Surround each portion of the log with escape sequences to display it
  90. in color on the terminal.
  91. -C, --commit
  92. Create a git commit with the changes when the operation is complete. A
  93. standard commit message is used which may need to be edited.
  94. -d, --defconfigs
  95. Specify a file containing a list of defconfigs to move. The defconfig
  96. files can be given with shell-style wildcards.
  97. -n, --dry-run
  98. Perform a trial run that does not make any changes. It is useful to
  99. see what is going to happen before one actually runs it.
  100. -e, --exit-on-error
  101. Exit immediately if Make exits with a non-zero status while processing
  102. a defconfig file.
  103. -s, --force-sync
  104. Do "make savedefconfig" forcibly for all the defconfig files.
  105. If not specified, "make savedefconfig" only occurs for cases
  106. where at least one CONFIG was moved.
  107. -S, --spl
  108. Look for moved config options in spl/include/autoconf.mk instead of
  109. include/autoconf.mk. This is useful for moving options for SPL build
  110. because SPL related options (mostly prefixed with CONFIG_SPL_) are
  111. sometimes blocked by CONFIG_SPL_BUILD ifdef conditionals.
  112. -H, --headers-only
  113. Only cleanup the headers; skip the defconfig processing
  114. -j, --jobs
  115. Specify the number of threads to run simultaneously. If not specified,
  116. the number of threads is the same as the number of CPU cores.
  117. -r, --git-ref
  118. Specify the git ref to clone for building the autoconf.mk. If unspecified
  119. use the CWD. This is useful for when changes to the Kconfig affect the
  120. default values and you want to capture the state of the defconfig from
  121. before that change was in effect. If in doubt, specify a ref pre-Kconfig
  122. changes (use HEAD if Kconfig changes are not committed). Worst case it will
  123. take a bit longer to run, but will always do the right thing.
  124. -v, --verbose
  125. Show any build errors as boards are built
  126. -y, --yes
  127. Instead of prompting, automatically go ahead with all operations. This
  128. includes cleaning up headers and CONFIG_SYS_EXTRA_OPTIONS.
  129. To see the complete list of supported options, run
  130. $ tools/moveconfig.py -h
  131. """
  132. import copy
  133. import difflib
  134. import filecmp
  135. import fnmatch
  136. import glob
  137. import multiprocessing
  138. import optparse
  139. import os
  140. import re
  141. import shutil
  142. import subprocess
  143. import sys
  144. import tempfile
  145. import time
  146. SHOW_GNU_MAKE = 'scripts/show-gnu-make'
  147. SLEEP_TIME=0.03
  148. # Here is the list of cross-tools I use.
  149. # Most of them are available at kernel.org
  150. # (https://www.kernel.org/pub/tools/crosstool/files/bin/), except the following:
  151. # arc: https://github.com/foss-for-synopsys-dwc-arc-processors/toolchain/releases
  152. # nds32: http://osdk.andestech.com/packages/nds32le-linux-glibc-v1.tgz
  153. # nios2: https://sourcery.mentor.com/GNUToolchain/subscription42545
  154. # sh: http://sourcery.mentor.com/public/gnu_toolchain/sh-linux-gnu
  155. CROSS_COMPILE = {
  156. 'arc': 'arc-linux-',
  157. 'aarch64': 'aarch64-linux-',
  158. 'arm': 'arm-unknown-linux-gnueabi-',
  159. 'avr32': 'avr32-linux-',
  160. 'm68k': 'm68k-linux-',
  161. 'microblaze': 'microblaze-linux-',
  162. 'mips': 'mips-linux-',
  163. 'nds32': 'nds32le-linux-',
  164. 'nios2': 'nios2-linux-gnu-',
  165. 'powerpc': 'powerpc-linux-',
  166. 'sh': 'sh-linux-gnu-',
  167. 'x86': 'i386-linux-',
  168. 'xtensa': 'xtensa-linux-'
  169. }
  170. STATE_IDLE = 0
  171. STATE_DEFCONFIG = 1
  172. STATE_AUTOCONF = 2
  173. STATE_SAVEDEFCONFIG = 3
  174. ACTION_MOVE = 0
  175. ACTION_NO_ENTRY = 1
  176. ACTION_NO_ENTRY_WARN = 2
  177. ACTION_NO_CHANGE = 3
  178. COLOR_BLACK = '0;30'
  179. COLOR_RED = '0;31'
  180. COLOR_GREEN = '0;32'
  181. COLOR_BROWN = '0;33'
  182. COLOR_BLUE = '0;34'
  183. COLOR_PURPLE = '0;35'
  184. COLOR_CYAN = '0;36'
  185. COLOR_LIGHT_GRAY = '0;37'
  186. COLOR_DARK_GRAY = '1;30'
  187. COLOR_LIGHT_RED = '1;31'
  188. COLOR_LIGHT_GREEN = '1;32'
  189. COLOR_YELLOW = '1;33'
  190. COLOR_LIGHT_BLUE = '1;34'
  191. COLOR_LIGHT_PURPLE = '1;35'
  192. COLOR_LIGHT_CYAN = '1;36'
  193. COLOR_WHITE = '1;37'
  194. ### helper functions ###
  195. def get_devnull():
  196. """Get the file object of '/dev/null' device."""
  197. try:
  198. devnull = subprocess.DEVNULL # py3k
  199. except AttributeError:
  200. devnull = open(os.devnull, 'wb')
  201. return devnull
  202. def check_top_directory():
  203. """Exit if we are not at the top of source directory."""
  204. for f in ('README', 'Licenses'):
  205. if not os.path.exists(f):
  206. sys.exit('Please run at the top of source directory.')
  207. def check_clean_directory():
  208. """Exit if the source tree is not clean."""
  209. for f in ('.config', 'include/config'):
  210. if os.path.exists(f):
  211. sys.exit("source tree is not clean, please run 'make mrproper'")
  212. def get_make_cmd():
  213. """Get the command name of GNU Make.
  214. U-Boot needs GNU Make for building, but the command name is not
  215. necessarily "make". (for example, "gmake" on FreeBSD).
  216. Returns the most appropriate command name on your system.
  217. """
  218. process = subprocess.Popen([SHOW_GNU_MAKE], stdout=subprocess.PIPE)
  219. ret = process.communicate()
  220. if process.returncode:
  221. sys.exit('GNU Make not found')
  222. return ret[0].rstrip()
  223. def get_matched_defconfigs(defconfigs_file):
  224. """Get all the defconfig files that match the patterns in a file."""
  225. defconfigs = []
  226. for i, line in enumerate(open(defconfigs_file)):
  227. line = line.strip()
  228. if not line:
  229. continue # skip blank lines silently
  230. pattern = os.path.join('configs', line)
  231. matched = glob.glob(pattern) + glob.glob(pattern + '_defconfig')
  232. if not matched:
  233. print >> sys.stderr, "warning: %s:%d: no defconfig matched '%s'" % \
  234. (defconfigs_file, i + 1, line)
  235. defconfigs += matched
  236. # use set() to drop multiple matching
  237. return [ defconfig[len('configs') + 1:] for defconfig in set(defconfigs) ]
  238. def get_all_defconfigs():
  239. """Get all the defconfig files under the configs/ directory."""
  240. defconfigs = []
  241. for (dirpath, dirnames, filenames) in os.walk('configs'):
  242. dirpath = dirpath[len('configs') + 1:]
  243. for filename in fnmatch.filter(filenames, '*_defconfig'):
  244. defconfigs.append(os.path.join(dirpath, filename))
  245. return defconfigs
  246. def color_text(color_enabled, color, string):
  247. """Return colored string."""
  248. if color_enabled:
  249. # LF should not be surrounded by the escape sequence.
  250. # Otherwise, additional whitespace or line-feed might be printed.
  251. return '\n'.join([ '\033[' + color + 'm' + s + '\033[0m' if s else ''
  252. for s in string.split('\n') ])
  253. else:
  254. return string
  255. def show_diff(a, b, file_path, color_enabled):
  256. """Show unidified diff.
  257. Arguments:
  258. a: A list of lines (before)
  259. b: A list of lines (after)
  260. file_path: Path to the file
  261. color_enabled: Display the diff in color
  262. """
  263. diff = difflib.unified_diff(a, b,
  264. fromfile=os.path.join('a', file_path),
  265. tofile=os.path.join('b', file_path))
  266. for line in diff:
  267. if line[0] == '-' and line[1] != '-':
  268. print color_text(color_enabled, COLOR_RED, line),
  269. elif line[0] == '+' and line[1] != '+':
  270. print color_text(color_enabled, COLOR_GREEN, line),
  271. else:
  272. print line,
  273. def update_cross_compile(color_enabled):
  274. """Update per-arch CROSS_COMPILE via environment variables
  275. The default CROSS_COMPILE values are available
  276. in the CROSS_COMPILE list above.
  277. You can override them via environment variables
  278. CROSS_COMPILE_{ARCH}.
  279. For example, if you want to override toolchain prefixes
  280. for ARM and PowerPC, you can do as follows in your shell:
  281. export CROSS_COMPILE_ARM=...
  282. export CROSS_COMPILE_POWERPC=...
  283. Then, this function checks if specified compilers really exist in your
  284. PATH environment.
  285. """
  286. archs = []
  287. for arch in os.listdir('arch'):
  288. if os.path.exists(os.path.join('arch', arch, 'Makefile')):
  289. archs.append(arch)
  290. # arm64 is a special case
  291. archs.append('aarch64')
  292. for arch in archs:
  293. env = 'CROSS_COMPILE_' + arch.upper()
  294. cross_compile = os.environ.get(env)
  295. if not cross_compile:
  296. cross_compile = CROSS_COMPILE.get(arch, '')
  297. for path in os.environ["PATH"].split(os.pathsep):
  298. gcc_path = os.path.join(path, cross_compile + 'gcc')
  299. if os.path.isfile(gcc_path) and os.access(gcc_path, os.X_OK):
  300. break
  301. else:
  302. print >> sys.stderr, color_text(color_enabled, COLOR_YELLOW,
  303. 'warning: %sgcc: not found in PATH. %s architecture boards will be skipped'
  304. % (cross_compile, arch))
  305. cross_compile = None
  306. CROSS_COMPILE[arch] = cross_compile
  307. def extend_matched_lines(lines, matched, pre_patterns, post_patterns, extend_pre,
  308. extend_post):
  309. """Extend matched lines if desired patterns are found before/after already
  310. matched lines.
  311. Arguments:
  312. lines: A list of lines handled.
  313. matched: A list of line numbers that have been already matched.
  314. (will be updated by this function)
  315. pre_patterns: A list of regular expression that should be matched as
  316. preamble.
  317. post_patterns: A list of regular expression that should be matched as
  318. postamble.
  319. extend_pre: Add the line number of matched preamble to the matched list.
  320. extend_post: Add the line number of matched postamble to the matched list.
  321. """
  322. extended_matched = []
  323. j = matched[0]
  324. for i in matched:
  325. if i == 0 or i < j:
  326. continue
  327. j = i
  328. while j in matched:
  329. j += 1
  330. if j >= len(lines):
  331. break
  332. for p in pre_patterns:
  333. if p.search(lines[i - 1]):
  334. break
  335. else:
  336. # not matched
  337. continue
  338. for p in post_patterns:
  339. if p.search(lines[j]):
  340. break
  341. else:
  342. # not matched
  343. continue
  344. if extend_pre:
  345. extended_matched.append(i - 1)
  346. if extend_post:
  347. extended_matched.append(j)
  348. matched += extended_matched
  349. matched.sort()
  350. def confirm(options, prompt):
  351. if not options.yes:
  352. while True:
  353. choice = raw_input('{} [y/n]: '.format(prompt))
  354. choice = choice.lower()
  355. print choice
  356. if choice == 'y' or choice == 'n':
  357. break
  358. if choice == 'n':
  359. return False
  360. return True
  361. def cleanup_one_header(header_path, patterns, options):
  362. """Clean regex-matched lines away from a file.
  363. Arguments:
  364. header_path: path to the cleaned file.
  365. patterns: list of regex patterns. Any lines matching to these
  366. patterns are deleted.
  367. options: option flags.
  368. """
  369. with open(header_path) as f:
  370. lines = f.readlines()
  371. matched = []
  372. for i, line in enumerate(lines):
  373. if i - 1 in matched and lines[i - 1][-2:] == '\\\n':
  374. matched.append(i)
  375. continue
  376. for pattern in patterns:
  377. if pattern.search(line):
  378. matched.append(i)
  379. break
  380. if not matched:
  381. return
  382. # remove empty #ifdef ... #endif, successive blank lines
  383. pattern_if = re.compile(r'#\s*if(def|ndef)?\W') # #if, #ifdef, #ifndef
  384. pattern_elif = re.compile(r'#\s*el(if|se)\W') # #elif, #else
  385. pattern_endif = re.compile(r'#\s*endif\W') # #endif
  386. pattern_blank = re.compile(r'^\s*$') # empty line
  387. while True:
  388. old_matched = copy.copy(matched)
  389. extend_matched_lines(lines, matched, [pattern_if],
  390. [pattern_endif], True, True)
  391. extend_matched_lines(lines, matched, [pattern_elif],
  392. [pattern_elif, pattern_endif], True, False)
  393. extend_matched_lines(lines, matched, [pattern_if, pattern_elif],
  394. [pattern_blank], False, True)
  395. extend_matched_lines(lines, matched, [pattern_blank],
  396. [pattern_elif, pattern_endif], True, False)
  397. extend_matched_lines(lines, matched, [pattern_blank],
  398. [pattern_blank], True, False)
  399. if matched == old_matched:
  400. break
  401. tolines = copy.copy(lines)
  402. for i in reversed(matched):
  403. tolines.pop(i)
  404. show_diff(lines, tolines, header_path, options.color)
  405. if options.dry_run:
  406. return
  407. with open(header_path, 'w') as f:
  408. for line in tolines:
  409. f.write(line)
  410. def cleanup_headers(configs, options):
  411. """Delete config defines from board headers.
  412. Arguments:
  413. configs: A list of CONFIGs to remove.
  414. options: option flags.
  415. """
  416. if not confirm(options, 'Clean up headers?'):
  417. return
  418. patterns = []
  419. for config in configs:
  420. patterns.append(re.compile(r'#\s*define\s+%s\W' % config))
  421. patterns.append(re.compile(r'#\s*undef\s+%s\W' % config))
  422. for dir in 'include', 'arch', 'board':
  423. for (dirpath, dirnames, filenames) in os.walk(dir):
  424. if dirpath == os.path.join('include', 'generated'):
  425. continue
  426. for filename in filenames:
  427. if not fnmatch.fnmatch(filename, '*~'):
  428. cleanup_one_header(os.path.join(dirpath, filename),
  429. patterns, options)
  430. def cleanup_one_extra_option(defconfig_path, configs, options):
  431. """Delete config defines in CONFIG_SYS_EXTRA_OPTIONS in one defconfig file.
  432. Arguments:
  433. defconfig_path: path to the cleaned defconfig file.
  434. configs: A list of CONFIGs to remove.
  435. options: option flags.
  436. """
  437. start = 'CONFIG_SYS_EXTRA_OPTIONS="'
  438. end = '"\n'
  439. with open(defconfig_path) as f:
  440. lines = f.readlines()
  441. for i, line in enumerate(lines):
  442. if line.startswith(start) and line.endswith(end):
  443. break
  444. else:
  445. # CONFIG_SYS_EXTRA_OPTIONS was not found in this defconfig
  446. return
  447. old_tokens = line[len(start):-len(end)].split(',')
  448. new_tokens = []
  449. for token in old_tokens:
  450. pos = token.find('=')
  451. if not (token[:pos] if pos >= 0 else token) in configs:
  452. new_tokens.append(token)
  453. if new_tokens == old_tokens:
  454. return
  455. tolines = copy.copy(lines)
  456. if new_tokens:
  457. tolines[i] = start + ','.join(new_tokens) + end
  458. else:
  459. tolines.pop(i)
  460. show_diff(lines, tolines, defconfig_path, options.color)
  461. if options.dry_run:
  462. return
  463. with open(defconfig_path, 'w') as f:
  464. for line in tolines:
  465. f.write(line)
  466. def cleanup_extra_options(configs, options):
  467. """Delete config defines in CONFIG_SYS_EXTRA_OPTIONS in defconfig files.
  468. Arguments:
  469. configs: A list of CONFIGs to remove.
  470. options: option flags.
  471. """
  472. if not confirm(options, 'Clean up CONFIG_SYS_EXTRA_OPTIONS?'):
  473. return
  474. configs = [ config[len('CONFIG_'):] for config in configs ]
  475. defconfigs = get_all_defconfigs()
  476. for defconfig in defconfigs:
  477. cleanup_one_extra_option(os.path.join('configs', defconfig), configs,
  478. options)
  479. def cleanup_whitelist(configs, options):
  480. """Delete config whitelist entries
  481. Arguments:
  482. configs: A list of CONFIGs to remove.
  483. options: option flags.
  484. """
  485. if not confirm(options, 'Clean up whitelist entries?'):
  486. return
  487. with open(os.path.join('scripts', 'config_whitelist.txt')) as f:
  488. lines = f.readlines()
  489. lines = [x for x in lines if x.strip() not in configs]
  490. with open(os.path.join('scripts', 'config_whitelist.txt'), 'w') as f:
  491. f.write(''.join(lines))
  492. def find_matching(patterns, line):
  493. for pat in patterns:
  494. if pat.search(line):
  495. return True
  496. return False
  497. def cleanup_readme(configs, options):
  498. """Delete config description in README
  499. Arguments:
  500. configs: A list of CONFIGs to remove.
  501. options: option flags.
  502. """
  503. if not confirm(options, 'Clean up README?'):
  504. return
  505. patterns = []
  506. for config in configs:
  507. patterns.append(re.compile(r'^\s+%s' % config))
  508. with open('README') as f:
  509. lines = f.readlines()
  510. found = False
  511. newlines = []
  512. for line in lines:
  513. if not found:
  514. found = find_matching(patterns, line)
  515. if found:
  516. continue
  517. if found and re.search(r'^\s+CONFIG', line):
  518. found = False
  519. if not found:
  520. newlines.append(line)
  521. with open('README', 'w') as f:
  522. f.write(''.join(newlines))
  523. ### classes ###
  524. class Progress:
  525. """Progress Indicator"""
  526. def __init__(self, total):
  527. """Create a new progress indicator.
  528. Arguments:
  529. total: A number of defconfig files to process.
  530. """
  531. self.current = 0
  532. self.total = total
  533. def inc(self):
  534. """Increment the number of processed defconfig files."""
  535. self.current += 1
  536. def show(self):
  537. """Display the progress."""
  538. print ' %d defconfigs out of %d\r' % (self.current, self.total),
  539. sys.stdout.flush()
  540. class KconfigParser:
  541. """A parser of .config and include/autoconf.mk."""
  542. re_arch = re.compile(r'CONFIG_SYS_ARCH="(.*)"')
  543. re_cpu = re.compile(r'CONFIG_SYS_CPU="(.*)"')
  544. def __init__(self, configs, options, build_dir):
  545. """Create a new parser.
  546. Arguments:
  547. configs: A list of CONFIGs to move.
  548. options: option flags.
  549. build_dir: Build directory.
  550. """
  551. self.configs = configs
  552. self.options = options
  553. self.dotconfig = os.path.join(build_dir, '.config')
  554. self.autoconf = os.path.join(build_dir, 'include', 'autoconf.mk')
  555. self.spl_autoconf = os.path.join(build_dir, 'spl', 'include',
  556. 'autoconf.mk')
  557. self.config_autoconf = os.path.join(build_dir, 'include', 'config',
  558. 'auto.conf')
  559. self.defconfig = os.path.join(build_dir, 'defconfig')
  560. def get_cross_compile(self):
  561. """Parse .config file and return CROSS_COMPILE.
  562. Returns:
  563. A string storing the compiler prefix for the architecture.
  564. Return a NULL string for architectures that do not require
  565. compiler prefix (Sandbox and native build is the case).
  566. Return None if the specified compiler is missing in your PATH.
  567. Caller should distinguish '' and None.
  568. """
  569. arch = ''
  570. cpu = ''
  571. for line in open(self.dotconfig):
  572. m = self.re_arch.match(line)
  573. if m:
  574. arch = m.group(1)
  575. continue
  576. m = self.re_cpu.match(line)
  577. if m:
  578. cpu = m.group(1)
  579. if not arch:
  580. return None
  581. # fix-up for aarch64
  582. if arch == 'arm' and cpu == 'armv8':
  583. arch = 'aarch64'
  584. return CROSS_COMPILE.get(arch, None)
  585. def parse_one_config(self, config, dotconfig_lines, autoconf_lines):
  586. """Parse .config, defconfig, include/autoconf.mk for one config.
  587. This function looks for the config options in the lines from
  588. defconfig, .config, and include/autoconf.mk in order to decide
  589. which action should be taken for this defconfig.
  590. Arguments:
  591. config: CONFIG name to parse.
  592. dotconfig_lines: lines from the .config file.
  593. autoconf_lines: lines from the include/autoconf.mk file.
  594. Returns:
  595. A tupple of the action for this defconfig and the line
  596. matched for the config.
  597. """
  598. not_set = '# %s is not set' % config
  599. for line in autoconf_lines:
  600. line = line.rstrip()
  601. if line.startswith(config + '='):
  602. new_val = line
  603. break
  604. else:
  605. new_val = not_set
  606. for line in dotconfig_lines:
  607. line = line.rstrip()
  608. if line.startswith(config + '=') or line == not_set:
  609. old_val = line
  610. break
  611. else:
  612. if new_val == not_set:
  613. return (ACTION_NO_ENTRY, config)
  614. else:
  615. return (ACTION_NO_ENTRY_WARN, config)
  616. # If this CONFIG is neither bool nor trisate
  617. if old_val[-2:] != '=y' and old_val[-2:] != '=m' and old_val != not_set:
  618. # tools/scripts/define2mk.sed changes '1' to 'y'.
  619. # This is a problem if the CONFIG is int type.
  620. # Check the type in Kconfig and handle it correctly.
  621. if new_val[-2:] == '=y':
  622. new_val = new_val[:-1] + '1'
  623. return (ACTION_NO_CHANGE if old_val == new_val else ACTION_MOVE,
  624. new_val)
  625. def update_dotconfig(self):
  626. """Parse files for the config options and update the .config.
  627. This function parses the generated .config and include/autoconf.mk
  628. searching the target options.
  629. Move the config option(s) to the .config as needed.
  630. Arguments:
  631. defconfig: defconfig name.
  632. Returns:
  633. Return a tuple of (updated flag, log string).
  634. The "updated flag" is True if the .config was updated, False
  635. otherwise. The "log string" shows what happend to the .config.
  636. """
  637. results = []
  638. updated = False
  639. suspicious = False
  640. rm_files = [self.config_autoconf, self.autoconf]
  641. if self.options.spl:
  642. if os.path.exists(self.spl_autoconf):
  643. autoconf_path = self.spl_autoconf
  644. rm_files.append(self.spl_autoconf)
  645. else:
  646. for f in rm_files:
  647. os.remove(f)
  648. return (updated, suspicious,
  649. color_text(self.options.color, COLOR_BROWN,
  650. "SPL is not enabled. Skipped.") + '\n')
  651. else:
  652. autoconf_path = self.autoconf
  653. with open(self.dotconfig) as f:
  654. dotconfig_lines = f.readlines()
  655. with open(autoconf_path) as f:
  656. autoconf_lines = f.readlines()
  657. for config in self.configs:
  658. result = self.parse_one_config(config, dotconfig_lines,
  659. autoconf_lines)
  660. results.append(result)
  661. log = ''
  662. for (action, value) in results:
  663. if action == ACTION_MOVE:
  664. actlog = "Move '%s'" % value
  665. log_color = COLOR_LIGHT_GREEN
  666. elif action == ACTION_NO_ENTRY:
  667. actlog = "%s is not defined in Kconfig. Do nothing." % value
  668. log_color = COLOR_LIGHT_BLUE
  669. elif action == ACTION_NO_ENTRY_WARN:
  670. actlog = "%s is not defined in Kconfig (suspicious). Do nothing." % value
  671. log_color = COLOR_YELLOW
  672. suspicious = True
  673. elif action == ACTION_NO_CHANGE:
  674. actlog = "'%s' is the same as the define in Kconfig. Do nothing." \
  675. % value
  676. log_color = COLOR_LIGHT_PURPLE
  677. elif action == ACTION_SPL_NOT_EXIST:
  678. actlog = "SPL is not enabled for this defconfig. Skip."
  679. log_color = COLOR_PURPLE
  680. else:
  681. sys.exit("Internal Error. This should not happen.")
  682. log += color_text(self.options.color, log_color, actlog) + '\n'
  683. with open(self.dotconfig, 'a') as f:
  684. for (action, value) in results:
  685. if action == ACTION_MOVE:
  686. f.write(value + '\n')
  687. updated = True
  688. self.results = results
  689. for f in rm_files:
  690. os.remove(f)
  691. return (updated, suspicious, log)
  692. def check_defconfig(self):
  693. """Check the defconfig after savedefconfig
  694. Returns:
  695. Return additional log if moved CONFIGs were removed again by
  696. 'make savedefconfig'.
  697. """
  698. log = ''
  699. with open(self.defconfig) as f:
  700. defconfig_lines = f.readlines()
  701. for (action, value) in self.results:
  702. if action != ACTION_MOVE:
  703. continue
  704. if not value + '\n' in defconfig_lines:
  705. log += color_text(self.options.color, COLOR_YELLOW,
  706. "'%s' was removed by savedefconfig.\n" %
  707. value)
  708. return log
  709. class Slot:
  710. """A slot to store a subprocess.
  711. Each instance of this class handles one subprocess.
  712. This class is useful to control multiple threads
  713. for faster processing.
  714. """
  715. def __init__(self, configs, options, progress, devnull, make_cmd, reference_src_dir):
  716. """Create a new process slot.
  717. Arguments:
  718. configs: A list of CONFIGs to move.
  719. options: option flags.
  720. progress: A progress indicator.
  721. devnull: A file object of '/dev/null'.
  722. make_cmd: command name of GNU Make.
  723. reference_src_dir: Determine the true starting config state from this
  724. source tree.
  725. """
  726. self.options = options
  727. self.progress = progress
  728. self.build_dir = tempfile.mkdtemp()
  729. self.devnull = devnull
  730. self.make_cmd = (make_cmd, 'O=' + self.build_dir)
  731. self.reference_src_dir = reference_src_dir
  732. self.parser = KconfigParser(configs, options, self.build_dir)
  733. self.state = STATE_IDLE
  734. self.failed_boards = set()
  735. self.suspicious_boards = set()
  736. def __del__(self):
  737. """Delete the working directory
  738. This function makes sure the temporary directory is cleaned away
  739. even if Python suddenly dies due to error. It should be done in here
  740. because it is guaranteed the destructor is always invoked when the
  741. instance of the class gets unreferenced.
  742. If the subprocess is still running, wait until it finishes.
  743. """
  744. if self.state != STATE_IDLE:
  745. while self.ps.poll() == None:
  746. pass
  747. shutil.rmtree(self.build_dir)
  748. def add(self, defconfig):
  749. """Assign a new subprocess for defconfig and add it to the slot.
  750. If the slot is vacant, create a new subprocess for processing the
  751. given defconfig and add it to the slot. Just returns False if
  752. the slot is occupied (i.e. the current subprocess is still running).
  753. Arguments:
  754. defconfig: defconfig name.
  755. Returns:
  756. Return True on success or False on failure
  757. """
  758. if self.state != STATE_IDLE:
  759. return False
  760. self.defconfig = defconfig
  761. self.log = ''
  762. self.current_src_dir = self.reference_src_dir
  763. self.do_defconfig()
  764. return True
  765. def poll(self):
  766. """Check the status of the subprocess and handle it as needed.
  767. Returns True if the slot is vacant (i.e. in idle state).
  768. If the configuration is successfully finished, assign a new
  769. subprocess to build include/autoconf.mk.
  770. If include/autoconf.mk is generated, invoke the parser to
  771. parse the .config and the include/autoconf.mk, moving
  772. config options to the .config as needed.
  773. If the .config was updated, run "make savedefconfig" to sync
  774. it, update the original defconfig, and then set the slot back
  775. to the idle state.
  776. Returns:
  777. Return True if the subprocess is terminated, False otherwise
  778. """
  779. if self.state == STATE_IDLE:
  780. return True
  781. if self.ps.poll() == None:
  782. return False
  783. if self.ps.poll() != 0:
  784. self.handle_error()
  785. elif self.state == STATE_DEFCONFIG:
  786. if self.reference_src_dir and not self.current_src_dir:
  787. self.do_savedefconfig()
  788. else:
  789. self.do_autoconf()
  790. elif self.state == STATE_AUTOCONF:
  791. if self.current_src_dir:
  792. self.current_src_dir = None
  793. self.do_defconfig()
  794. else:
  795. self.do_savedefconfig()
  796. elif self.state == STATE_SAVEDEFCONFIG:
  797. self.update_defconfig()
  798. else:
  799. sys.exit("Internal Error. This should not happen.")
  800. return True if self.state == STATE_IDLE else False
  801. def handle_error(self):
  802. """Handle error cases."""
  803. self.log += color_text(self.options.color, COLOR_LIGHT_RED,
  804. "Failed to process.\n")
  805. if self.options.verbose:
  806. self.log += color_text(self.options.color, COLOR_LIGHT_CYAN,
  807. self.ps.stderr.read())
  808. self.finish(False)
  809. def do_defconfig(self):
  810. """Run 'make <board>_defconfig' to create the .config file."""
  811. cmd = list(self.make_cmd)
  812. cmd.append(self.defconfig)
  813. self.ps = subprocess.Popen(cmd, stdout=self.devnull,
  814. stderr=subprocess.PIPE,
  815. cwd=self.current_src_dir)
  816. self.state = STATE_DEFCONFIG
  817. def do_autoconf(self):
  818. """Run 'make include/config/auto.conf'."""
  819. self.cross_compile = self.parser.get_cross_compile()
  820. if self.cross_compile is None:
  821. self.log += color_text(self.options.color, COLOR_YELLOW,
  822. "Compiler is missing. Do nothing.\n")
  823. self.finish(False)
  824. return
  825. cmd = list(self.make_cmd)
  826. if self.cross_compile:
  827. cmd.append('CROSS_COMPILE=%s' % self.cross_compile)
  828. cmd.append('KCONFIG_IGNORE_DUPLICATES=1')
  829. cmd.append('include/config/auto.conf')
  830. self.ps = subprocess.Popen(cmd, stdout=self.devnull,
  831. stderr=subprocess.PIPE,
  832. cwd=self.current_src_dir)
  833. self.state = STATE_AUTOCONF
  834. def do_savedefconfig(self):
  835. """Update the .config and run 'make savedefconfig'."""
  836. (updated, suspicious, log) = self.parser.update_dotconfig()
  837. if suspicious:
  838. self.suspicious_boards.add(self.defconfig)
  839. self.log += log
  840. if not self.options.force_sync and not updated:
  841. self.finish(True)
  842. return
  843. if updated:
  844. self.log += color_text(self.options.color, COLOR_LIGHT_GREEN,
  845. "Syncing by savedefconfig...\n")
  846. else:
  847. self.log += "Syncing by savedefconfig (forced by option)...\n"
  848. cmd = list(self.make_cmd)
  849. cmd.append('savedefconfig')
  850. self.ps = subprocess.Popen(cmd, stdout=self.devnull,
  851. stderr=subprocess.PIPE)
  852. self.state = STATE_SAVEDEFCONFIG
  853. def update_defconfig(self):
  854. """Update the input defconfig and go back to the idle state."""
  855. log = self.parser.check_defconfig()
  856. if log:
  857. self.suspicious_boards.add(self.defconfig)
  858. self.log += log
  859. orig_defconfig = os.path.join('configs', self.defconfig)
  860. new_defconfig = os.path.join(self.build_dir, 'defconfig')
  861. updated = not filecmp.cmp(orig_defconfig, new_defconfig)
  862. if updated:
  863. self.log += color_text(self.options.color, COLOR_LIGHT_BLUE,
  864. "defconfig was updated.\n")
  865. if not self.options.dry_run and updated:
  866. shutil.move(new_defconfig, orig_defconfig)
  867. self.finish(True)
  868. def finish(self, success):
  869. """Display log along with progress and go to the idle state.
  870. Arguments:
  871. success: Should be True when the defconfig was processed
  872. successfully, or False when it fails.
  873. """
  874. # output at least 30 characters to hide the "* defconfigs out of *".
  875. log = self.defconfig.ljust(30) + '\n'
  876. log += '\n'.join([ ' ' + s for s in self.log.split('\n') ])
  877. # Some threads are running in parallel.
  878. # Print log atomically to not mix up logs from different threads.
  879. print >> (sys.stdout if success else sys.stderr), log
  880. if not success:
  881. if self.options.exit_on_error:
  882. sys.exit("Exit on error.")
  883. # If --exit-on-error flag is not set, skip this board and continue.
  884. # Record the failed board.
  885. self.failed_boards.add(self.defconfig)
  886. self.progress.inc()
  887. self.progress.show()
  888. self.state = STATE_IDLE
  889. def get_failed_boards(self):
  890. """Returns a set of failed boards (defconfigs) in this slot.
  891. """
  892. return self.failed_boards
  893. def get_suspicious_boards(self):
  894. """Returns a set of boards (defconfigs) with possible misconversion.
  895. """
  896. return self.suspicious_boards - self.failed_boards
  897. class Slots:
  898. """Controller of the array of subprocess slots."""
  899. def __init__(self, configs, options, progress, reference_src_dir):
  900. """Create a new slots controller.
  901. Arguments:
  902. configs: A list of CONFIGs to move.
  903. options: option flags.
  904. progress: A progress indicator.
  905. reference_src_dir: Determine the true starting config state from this
  906. source tree.
  907. """
  908. self.options = options
  909. self.slots = []
  910. devnull = get_devnull()
  911. make_cmd = get_make_cmd()
  912. for i in range(options.jobs):
  913. self.slots.append(Slot(configs, options, progress, devnull,
  914. make_cmd, reference_src_dir))
  915. def add(self, defconfig):
  916. """Add a new subprocess if a vacant slot is found.
  917. Arguments:
  918. defconfig: defconfig name to be put into.
  919. Returns:
  920. Return True on success or False on failure
  921. """
  922. for slot in self.slots:
  923. if slot.add(defconfig):
  924. return True
  925. return False
  926. def available(self):
  927. """Check if there is a vacant slot.
  928. Returns:
  929. Return True if at lease one vacant slot is found, False otherwise.
  930. """
  931. for slot in self.slots:
  932. if slot.poll():
  933. return True
  934. return False
  935. def empty(self):
  936. """Check if all slots are vacant.
  937. Returns:
  938. Return True if all the slots are vacant, False otherwise.
  939. """
  940. ret = True
  941. for slot in self.slots:
  942. if not slot.poll():
  943. ret = False
  944. return ret
  945. def show_failed_boards(self):
  946. """Display all of the failed boards (defconfigs)."""
  947. boards = set()
  948. output_file = 'moveconfig.failed'
  949. for slot in self.slots:
  950. boards |= slot.get_failed_boards()
  951. if boards:
  952. boards = '\n'.join(boards) + '\n'
  953. msg = "The following boards were not processed due to error:\n"
  954. msg += boards
  955. msg += "(the list has been saved in %s)\n" % output_file
  956. print >> sys.stderr, color_text(self.options.color, COLOR_LIGHT_RED,
  957. msg)
  958. with open(output_file, 'w') as f:
  959. f.write(boards)
  960. def show_suspicious_boards(self):
  961. """Display all boards (defconfigs) with possible misconversion."""
  962. boards = set()
  963. output_file = 'moveconfig.suspicious'
  964. for slot in self.slots:
  965. boards |= slot.get_suspicious_boards()
  966. if boards:
  967. boards = '\n'.join(boards) + '\n'
  968. msg = "The following boards might have been converted incorrectly.\n"
  969. msg += "It is highly recommended to check them manually:\n"
  970. msg += boards
  971. msg += "(the list has been saved in %s)\n" % output_file
  972. print >> sys.stderr, color_text(self.options.color, COLOR_YELLOW,
  973. msg)
  974. with open(output_file, 'w') as f:
  975. f.write(boards)
  976. class ReferenceSource:
  977. """Reference source against which original configs should be parsed."""
  978. def __init__(self, commit):
  979. """Create a reference source directory based on a specified commit.
  980. Arguments:
  981. commit: commit to git-clone
  982. """
  983. self.src_dir = tempfile.mkdtemp()
  984. print "Cloning git repo to a separate work directory..."
  985. subprocess.check_output(['git', 'clone', os.getcwd(), '.'],
  986. cwd=self.src_dir)
  987. print "Checkout '%s' to build the original autoconf.mk." % \
  988. subprocess.check_output(['git', 'rev-parse', '--short', commit]).strip()
  989. subprocess.check_output(['git', 'checkout', commit],
  990. stderr=subprocess.STDOUT, cwd=self.src_dir)
  991. def __del__(self):
  992. """Delete the reference source directory
  993. This function makes sure the temporary directory is cleaned away
  994. even if Python suddenly dies due to error. It should be done in here
  995. because it is guaranteed the destructor is always invoked when the
  996. instance of the class gets unreferenced.
  997. """
  998. shutil.rmtree(self.src_dir)
  999. def get_dir(self):
  1000. """Return the absolute path to the reference source directory."""
  1001. return self.src_dir
  1002. def move_config(configs, options):
  1003. """Move config options to defconfig files.
  1004. Arguments:
  1005. configs: A list of CONFIGs to move.
  1006. options: option flags
  1007. """
  1008. if len(configs) == 0:
  1009. if options.force_sync:
  1010. print 'No CONFIG is specified. You are probably syncing defconfigs.',
  1011. else:
  1012. print 'Neither CONFIG nor --force-sync is specified. Nothing will happen.',
  1013. else:
  1014. print 'Move ' + ', '.join(configs),
  1015. print '(jobs: %d)\n' % options.jobs
  1016. if options.git_ref:
  1017. reference_src = ReferenceSource(options.git_ref)
  1018. reference_src_dir = reference_src.get_dir()
  1019. else:
  1020. reference_src_dir = None
  1021. if options.defconfigs:
  1022. defconfigs = get_matched_defconfigs(options.defconfigs)
  1023. else:
  1024. defconfigs = get_all_defconfigs()
  1025. progress = Progress(len(defconfigs))
  1026. slots = Slots(configs, options, progress, reference_src_dir)
  1027. # Main loop to process defconfig files:
  1028. # Add a new subprocess into a vacant slot.
  1029. # Sleep if there is no available slot.
  1030. for defconfig in defconfigs:
  1031. while not slots.add(defconfig):
  1032. while not slots.available():
  1033. # No available slot: sleep for a while
  1034. time.sleep(SLEEP_TIME)
  1035. # wait until all the subprocesses finish
  1036. while not slots.empty():
  1037. time.sleep(SLEEP_TIME)
  1038. print ''
  1039. slots.show_failed_boards()
  1040. slots.show_suspicious_boards()
  1041. def main():
  1042. try:
  1043. cpu_count = multiprocessing.cpu_count()
  1044. except NotImplementedError:
  1045. cpu_count = 1
  1046. parser = optparse.OptionParser()
  1047. # Add options here
  1048. parser.add_option('-c', '--color', action='store_true', default=False,
  1049. help='display the log in color')
  1050. parser.add_option('-C', '--commit', action='store_true', default=False,
  1051. help='Create a git commit for the operation')
  1052. parser.add_option('-d', '--defconfigs', type='string',
  1053. help='a file containing a list of defconfigs to move')
  1054. parser.add_option('-n', '--dry-run', action='store_true', default=False,
  1055. help='perform a trial run (show log with no changes)')
  1056. parser.add_option('-e', '--exit-on-error', action='store_true',
  1057. default=False,
  1058. help='exit immediately on any error')
  1059. parser.add_option('-s', '--force-sync', action='store_true', default=False,
  1060. help='force sync by savedefconfig')
  1061. parser.add_option('-S', '--spl', action='store_true', default=False,
  1062. help='parse config options defined for SPL build')
  1063. parser.add_option('-H', '--headers-only', dest='cleanup_headers_only',
  1064. action='store_true', default=False,
  1065. help='only cleanup the headers')
  1066. parser.add_option('-j', '--jobs', type='int', default=cpu_count,
  1067. help='the number of jobs to run simultaneously')
  1068. parser.add_option('-r', '--git-ref', type='string',
  1069. help='the git ref to clone for building the autoconf.mk')
  1070. parser.add_option('-y', '--yes', action='store_true', default=False,
  1071. help="respond 'yes' to any prompts")
  1072. parser.add_option('-v', '--verbose', action='store_true', default=False,
  1073. help='show any build errors as boards are built')
  1074. parser.usage += ' CONFIG ...'
  1075. (options, configs) = parser.parse_args()
  1076. if len(configs) == 0 and not options.force_sync:
  1077. parser.print_usage()
  1078. sys.exit(1)
  1079. # prefix the option name with CONFIG_ if missing
  1080. configs = [ config if config.startswith('CONFIG_') else 'CONFIG_' + config
  1081. for config in configs ]
  1082. check_top_directory()
  1083. if not options.cleanup_headers_only:
  1084. check_clean_directory()
  1085. update_cross_compile(options.color)
  1086. move_config(configs, options)
  1087. if configs:
  1088. cleanup_headers(configs, options)
  1089. cleanup_extra_options(configs, options)
  1090. cleanup_whitelist(configs, options)
  1091. cleanup_readme(configs, options)
  1092. if options.commit:
  1093. subprocess.call(['git', 'add', '-u'])
  1094. if configs:
  1095. msg = 'Convert %s %sto Kconfig' % (configs[0],
  1096. 'et al ' if len(configs) > 1 else '')
  1097. msg += ('\n\nThis converts the following to Kconfig:\n %s\n' %
  1098. '\n '.join(configs))
  1099. else:
  1100. msg = 'configs: Resync with savedefconfig'
  1101. msg += '\n\nRsync all defconfig files using moveconfig.py'
  1102. subprocess.call(['git', 'commit', '-s', '-m', msg])
  1103. if __name__ == '__main__':
  1104. main()