moveconfig.py 44 KB

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