moveconfig.py 44 KB

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