moveconfig.py 44 KB

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