moveconfig.py 41 KB

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