moveconfig.py 71 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072
  1. #!/usr/bin/env python3
  2. # SPDX-License-Identifier: GPL-2.0+
  3. #
  4. # Author: Masahiro Yamada <yamada.masahiro@socionext.com>
  5. #
  6. """
  7. Move config options from headers to defconfig files.
  8. See doc/develop/moveconfig.rst for documentation.
  9. """
  10. from argparse import ArgumentParser
  11. import asteval
  12. import collections
  13. from contextlib import ExitStack
  14. import copy
  15. import difflib
  16. import doctest
  17. import filecmp
  18. import fnmatch
  19. import glob
  20. import multiprocessing
  21. import os
  22. import queue
  23. import re
  24. import shutil
  25. import subprocess
  26. import sys
  27. import tempfile
  28. import threading
  29. import time
  30. import unittest
  31. from buildman import bsettings
  32. from buildman import kconfiglib
  33. from buildman import toolchain
  34. SHOW_GNU_MAKE = 'scripts/show-gnu-make'
  35. SLEEP_TIME=0.03
  36. STATE_IDLE = 0
  37. STATE_DEFCONFIG = 1
  38. STATE_AUTOCONF = 2
  39. STATE_SAVEDEFCONFIG = 3
  40. ACTION_MOVE = 0
  41. ACTION_NO_ENTRY = 1
  42. ACTION_NO_ENTRY_WARN = 2
  43. ACTION_NO_CHANGE = 3
  44. COLOR_BLACK = '0;30'
  45. COLOR_RED = '0;31'
  46. COLOR_GREEN = '0;32'
  47. COLOR_BROWN = '0;33'
  48. COLOR_BLUE = '0;34'
  49. COLOR_PURPLE = '0;35'
  50. COLOR_CYAN = '0;36'
  51. COLOR_LIGHT_GRAY = '0;37'
  52. COLOR_DARK_GRAY = '1;30'
  53. COLOR_LIGHT_RED = '1;31'
  54. COLOR_LIGHT_GREEN = '1;32'
  55. COLOR_YELLOW = '1;33'
  56. COLOR_LIGHT_BLUE = '1;34'
  57. COLOR_LIGHT_PURPLE = '1;35'
  58. COLOR_LIGHT_CYAN = '1;36'
  59. COLOR_WHITE = '1;37'
  60. AUTO_CONF_PATH = 'include/config/auto.conf'
  61. CONFIG_DATABASE = 'moveconfig.db'
  62. CONFIG_LEN = len('CONFIG_')
  63. SIZES = {
  64. 'SZ_1': 0x00000001, 'SZ_2': 0x00000002,
  65. 'SZ_4': 0x00000004, 'SZ_8': 0x00000008,
  66. 'SZ_16': 0x00000010, 'SZ_32': 0x00000020,
  67. 'SZ_64': 0x00000040, 'SZ_128': 0x00000080,
  68. 'SZ_256': 0x00000100, 'SZ_512': 0x00000200,
  69. 'SZ_1K': 0x00000400, 'SZ_2K': 0x00000800,
  70. 'SZ_4K': 0x00001000, 'SZ_8K': 0x00002000,
  71. 'SZ_16K': 0x00004000, 'SZ_32K': 0x00008000,
  72. 'SZ_64K': 0x00010000, 'SZ_128K': 0x00020000,
  73. 'SZ_256K': 0x00040000, 'SZ_512K': 0x00080000,
  74. 'SZ_1M': 0x00100000, 'SZ_2M': 0x00200000,
  75. 'SZ_4M': 0x00400000, 'SZ_8M': 0x00800000,
  76. 'SZ_16M': 0x01000000, 'SZ_32M': 0x02000000,
  77. 'SZ_64M': 0x04000000, 'SZ_128M': 0x08000000,
  78. 'SZ_256M': 0x10000000, 'SZ_512M': 0x20000000,
  79. 'SZ_1G': 0x40000000, 'SZ_2G': 0x80000000,
  80. 'SZ_4G': 0x100000000
  81. }
  82. RE_REMOVE_DEFCONFIG = re.compile(r'(.*)_defconfig')
  83. # CONFIG symbols present in the build system (from Linux) but not actually used
  84. # in U-Boot; KCONFIG symbols
  85. IGNORE_SYMS = ['DEBUG_SECTION_MISMATCH', 'FTRACE_MCOUNT_RECORD', 'GCOV_KERNEL',
  86. 'GCOV_PROFILE_ALL', 'KALLSYMS', 'KASAN', 'MODVERSIONS', 'SHELL',
  87. 'TPL_BUILD', 'VPL_BUILD', 'IS_ENABLED', 'FOO', 'IF_ENABLED_INT',
  88. 'IS_ENABLED_', 'IS_ENABLED_1', 'IS_ENABLED_2', 'IS_ENABLED_3',
  89. 'SPL_', 'TPL_', 'SPL_FOO', 'TPL_FOO', 'TOOLS_FOO',
  90. 'ACME', 'SPL_ACME', 'TPL_ACME', 'TRACE_BRANCH_PROFILING',
  91. 'VAL', '_UNDEFINED', 'SPL_BUILD', ]
  92. SPL_PREFIXES = ['SPL_', 'TPL_', 'VPL_', 'TOOLS_']
  93. ### helper functions ###
  94. def check_top_directory():
  95. """Exit if we are not at the top of source directory."""
  96. for fname in 'README', 'Licenses':
  97. if not os.path.exists(fname):
  98. sys.exit('Please run at the top of source directory.')
  99. def check_clean_directory():
  100. """Exit if the source tree is not clean."""
  101. for fname in '.config', 'include/config':
  102. if os.path.exists(fname):
  103. sys.exit("source tree is not clean, please run 'make mrproper'")
  104. def get_make_cmd():
  105. """Get the command name of GNU Make.
  106. U-Boot needs GNU Make for building, but the command name is not
  107. necessarily "make". (for example, "gmake" on FreeBSD).
  108. Returns the most appropriate command name on your system.
  109. """
  110. with subprocess.Popen([SHOW_GNU_MAKE], stdout=subprocess.PIPE) as proc:
  111. ret = proc.communicate()
  112. if proc.returncode:
  113. sys.exit('GNU Make not found')
  114. return ret[0].rstrip()
  115. def get_matched_defconfig(line):
  116. """Get the defconfig files that match a pattern
  117. Args:
  118. line (str): Path or filename to match, e.g. 'configs/snow_defconfig' or
  119. 'k2*_defconfig'. If no directory is provided, 'configs/' is
  120. prepended
  121. Returns:
  122. list of str: a list of matching defconfig files
  123. """
  124. dirname = os.path.dirname(line)
  125. if dirname:
  126. pattern = line
  127. else:
  128. pattern = os.path.join('configs', line)
  129. return glob.glob(pattern) + glob.glob(pattern + '_defconfig')
  130. def get_matched_defconfigs(defconfigs_file):
  131. """Get all the defconfig files that match the patterns in a file.
  132. Args:
  133. defconfigs_file (str): File containing a list of defconfigs to process,
  134. or '-' to read the list from stdin
  135. Returns:
  136. list of str: A list of paths to defconfig files, with no duplicates
  137. """
  138. defconfigs = []
  139. with ExitStack() as stack:
  140. if defconfigs_file == '-':
  141. inf = sys.stdin
  142. defconfigs_file = 'stdin'
  143. else:
  144. inf = stack.enter_context(open(defconfigs_file, encoding='utf-8'))
  145. for i, line in enumerate(inf):
  146. line = line.strip()
  147. if not line:
  148. continue # skip blank lines silently
  149. if ' ' in line:
  150. line = line.split(' ')[0] # handle 'git log' input
  151. matched = get_matched_defconfig(line)
  152. if not matched:
  153. print(f"warning: {defconfigs_file}:{i + 1}: no defconfig matched '{line}'",
  154. file=sys.stderr)
  155. defconfigs += matched
  156. # use set() to drop multiple matching
  157. return [defconfig[len('configs') + 1:] for defconfig in set(defconfigs)]
  158. def get_all_defconfigs():
  159. """Get all the defconfig files under the configs/ directory.
  160. Returns:
  161. list of str: List of paths to defconfig files
  162. """
  163. defconfigs = []
  164. for (dirpath, _, filenames) in os.walk('configs'):
  165. dirpath = dirpath[len('configs') + 1:]
  166. for filename in fnmatch.filter(filenames, '*_defconfig'):
  167. defconfigs.append(os.path.join(dirpath, filename))
  168. return defconfigs
  169. def color_text(color_enabled, color, string):
  170. """Return colored string."""
  171. if color_enabled:
  172. # LF should not be surrounded by the escape sequence.
  173. # Otherwise, additional whitespace or line-feed might be printed.
  174. return '\n'.join([ '\033[' + color + 'm' + s + '\033[0m' if s else ''
  175. for s in string.split('\n') ])
  176. return string
  177. def show_diff(alines, blines, file_path, color_enabled):
  178. """Show unidified diff.
  179. Args:
  180. alines (list of str): A list of lines (before)
  181. blines (list of str): A list of lines (after)
  182. file_path (str): Path to the file
  183. color_enabled (bool): Display the diff in color
  184. """
  185. diff = difflib.unified_diff(alines, blines,
  186. fromfile=os.path.join('a', file_path),
  187. tofile=os.path.join('b', file_path))
  188. for line in diff:
  189. if line.startswith('-') and not line.startswith('--'):
  190. print(color_text(color_enabled, COLOR_RED, line))
  191. elif line.startswith('+') and not line.startswith('++'):
  192. print(color_text(color_enabled, COLOR_GREEN, line))
  193. else:
  194. print(line)
  195. def extend_matched_lines(lines, matched, pre_patterns, post_patterns,
  196. extend_pre, extend_post):
  197. """Extend matched lines if desired patterns are found before/after already
  198. matched lines.
  199. Args:
  200. lines (list of str): list of lines handled.
  201. matched (list of int): list of line numbers that have been already
  202. matched (will be updated by this function)
  203. pre_patterns (list of re.Pattern): list of regular expression that should
  204. be matched as preamble
  205. post_patterns (list of re.Pattern): list of regular expression that should
  206. be matched as postamble
  207. extend_pre (bool): Add the line number of matched preamble to the matched
  208. list
  209. extend_post (bool): Add the line number of matched postamble to the
  210. matched list
  211. """
  212. extended_matched = []
  213. j = matched[0]
  214. for i in matched:
  215. if i == 0 or i < j:
  216. continue
  217. j = i
  218. while j in matched:
  219. j += 1
  220. if j >= len(lines):
  221. break
  222. for pat in pre_patterns:
  223. if pat.search(lines[i - 1]):
  224. break
  225. else:
  226. # not matched
  227. continue
  228. for pat in post_patterns:
  229. if pat.search(lines[j]):
  230. break
  231. else:
  232. # not matched
  233. continue
  234. if extend_pre:
  235. extended_matched.append(i - 1)
  236. if extend_post:
  237. extended_matched.append(j)
  238. matched += extended_matched
  239. matched.sort()
  240. def confirm(args, prompt):
  241. """Ask the user to confirm something
  242. Args:
  243. args (Namespace ): program arguments
  244. Returns:
  245. bool: True to confirm, False to cancel/stop
  246. """
  247. if not args.yes:
  248. while True:
  249. choice = input(f'{prompt} [y/n]: ')
  250. choice = choice.lower()
  251. print(choice)
  252. if choice in ('y', 'n'):
  253. break
  254. if choice == 'n':
  255. return False
  256. return True
  257. def write_file(fname, data):
  258. """Write data to a file
  259. Args:
  260. fname (str): Filename to write to
  261. data (list of str): Lines to write (with or without trailing newline);
  262. or str to write
  263. """
  264. with open(fname, 'w', encoding='utf-8') as out:
  265. if isinstance(data, list):
  266. for line in data:
  267. print(line.rstrip('\n'), file=out)
  268. else:
  269. out.write(data)
  270. def read_file(fname, as_lines=True, skip_unicode=False):
  271. """Read a file and return the contents
  272. Args:
  273. fname (str): Filename to read from
  274. as_lines: Return file contents as a list of lines
  275. skip_unicode (bool): True to report unicode errors and continue
  276. Returns:
  277. iter of str: List of ;ines from the file with newline removed; str if
  278. as_lines is False with newlines intact; or None if a unicode error
  279. occurred
  280. Raises:
  281. UnicodeDecodeError: Unicode error occurred when reading
  282. """
  283. with open(fname, encoding='utf-8') as inf:
  284. try:
  285. if as_lines:
  286. return [line.rstrip('\n') for line in inf.readlines()]
  287. else:
  288. return inf.read()
  289. except UnicodeDecodeError as e:
  290. if not skip_unicode:
  291. raise
  292. print("Failed on file %s': %s" % (fname, e))
  293. return None
  294. def cleanup_empty_blocks(header_path, args):
  295. """Clean up empty conditional blocks
  296. Args:
  297. header_path (str): path to the cleaned file.
  298. args (Namespace): program arguments
  299. """
  300. pattern = re.compile(r'^\s*#\s*if.*$\n^\s*#\s*endif.*$\n*', flags=re.M)
  301. data = read_file(header_path, as_lines=False, skip_unicode=True)
  302. if data is None:
  303. return
  304. new_data = pattern.sub('\n', data)
  305. show_diff(data.splitlines(True), new_data.splitlines(True), header_path,
  306. args.color)
  307. if args.dry_run:
  308. return
  309. if new_data != data:
  310. write_file(header_path, new_data)
  311. def cleanup_one_header(header_path, patterns, args):
  312. """Clean regex-matched lines away from a file.
  313. Args:
  314. header_path: path to the cleaned file.
  315. patterns: list of regex patterns. Any lines matching to these
  316. patterns are deleted.
  317. args (Namespace): program arguments
  318. """
  319. lines = read_file(header_path, skip_unicode=True)
  320. if lines is None:
  321. return
  322. matched = []
  323. for i, line in enumerate(lines):
  324. if i - 1 in matched and lines[i - 1].endswith('\\'):
  325. matched.append(i)
  326. continue
  327. for pattern in patterns:
  328. if pattern.search(line):
  329. matched.append(i)
  330. break
  331. if not matched:
  332. return
  333. # remove empty #ifdef ... #endif, successive blank lines
  334. pattern_if = re.compile(r'#\s*if(def|ndef)?\b') # #if, #ifdef, #ifndef
  335. pattern_elif = re.compile(r'#\s*el(if|se)\b') # #elif, #else
  336. pattern_endif = re.compile(r'#\s*endif\b') # #endif
  337. pattern_blank = re.compile(r'^\s*$') # empty line
  338. while True:
  339. old_matched = copy.copy(matched)
  340. extend_matched_lines(lines, matched, [pattern_if],
  341. [pattern_endif], True, True)
  342. extend_matched_lines(lines, matched, [pattern_elif],
  343. [pattern_elif, pattern_endif], True, False)
  344. extend_matched_lines(lines, matched, [pattern_if, pattern_elif],
  345. [pattern_blank], False, True)
  346. extend_matched_lines(lines, matched, [pattern_blank],
  347. [pattern_elif, pattern_endif], True, False)
  348. extend_matched_lines(lines, matched, [pattern_blank],
  349. [pattern_blank], True, False)
  350. if matched == old_matched:
  351. break
  352. tolines = copy.copy(lines)
  353. for i in reversed(matched):
  354. tolines.pop(i)
  355. show_diff(lines, tolines, header_path, args.color)
  356. if args.dry_run:
  357. return
  358. write_file(header_path, tolines)
  359. def cleanup_headers(configs, args):
  360. """Delete config defines from board headers.
  361. Args:
  362. configs: A list of CONFIGs to remove.
  363. args (Namespace): program arguments
  364. """
  365. if not confirm(args, 'Clean up headers?'):
  366. return
  367. patterns = []
  368. for config in configs:
  369. patterns.append(re.compile(r'#\s*define\s+%s\b' % config))
  370. patterns.append(re.compile(r'#\s*undef\s+%s\b' % config))
  371. for dir in 'include', 'arch', 'board':
  372. for (dirpath, dirnames, filenames) in os.walk(dir):
  373. if dirpath == os.path.join('include', 'generated'):
  374. continue
  375. for filename in filenames:
  376. if not filename.endswith(('~', '.dts', '.dtsi', '.bin',
  377. '.elf','.aml','.dat')):
  378. header_path = os.path.join(dirpath, filename)
  379. # This file contains UTF-16 data and no CONFIG symbols
  380. if header_path == 'include/video_font_data.h':
  381. continue
  382. cleanup_one_header(header_path, patterns, args)
  383. cleanup_empty_blocks(header_path, args)
  384. def find_matching(patterns, line):
  385. for pat in patterns:
  386. if pat.search(line):
  387. return True
  388. return False
  389. def cleanup_readme(configs, args):
  390. """Delete config description in README
  391. Args:
  392. configs: A list of CONFIGs to remove.
  393. args (Namespace): program arguments
  394. """
  395. if not confirm(args, 'Clean up README?'):
  396. return
  397. patterns = []
  398. for config in configs:
  399. patterns.append(re.compile(r'^\s+%s' % config))
  400. lines = read_file('README')
  401. found = False
  402. newlines = []
  403. for line in lines:
  404. if not found:
  405. found = find_matching(patterns, line)
  406. if found:
  407. continue
  408. if found and re.search(r'^\s+CONFIG', line):
  409. found = False
  410. if not found:
  411. newlines.append(line)
  412. write_file('README', newlines)
  413. def try_expand(line):
  414. """If value looks like an expression, try expanding it
  415. Otherwise just return the existing value
  416. """
  417. if line.find('=') == -1:
  418. return line
  419. try:
  420. aeval = asteval.Interpreter( usersyms=SIZES, minimal=True )
  421. cfg, val = re.split("=", line)
  422. val= val.strip('\"')
  423. if re.search(r'[*+-/]|<<|SZ_+|\(([^\)]+)\)', val):
  424. newval = hex(aeval(val))
  425. print('\tExpanded expression %s to %s' % (val, newval))
  426. return cfg+'='+newval
  427. except:
  428. print('\tFailed to expand expression in %s' % line)
  429. return line
  430. ### classes ###
  431. class Progress:
  432. """Progress Indicator"""
  433. def __init__(self, total):
  434. """Create a new progress indicator.
  435. Args:
  436. total: A number of defconfig files to process.
  437. """
  438. self.current = 0
  439. self.total = total
  440. def inc(self):
  441. """Increment the number of processed defconfig files."""
  442. self.current += 1
  443. def show(self):
  444. """Display the progress."""
  445. print(' %d defconfigs out of %d\r' % (self.current, self.total), end=' ')
  446. sys.stdout.flush()
  447. class KconfigScanner:
  448. """Kconfig scanner."""
  449. def __init__(self):
  450. """Scan all the Kconfig files and create a Config object."""
  451. # Define environment variables referenced from Kconfig
  452. os.environ['srctree'] = os.getcwd()
  453. os.environ['UBOOTVERSION'] = 'dummy'
  454. os.environ['KCONFIG_OBJDIR'] = ''
  455. os.environ['CC'] = 'gcc'
  456. self.conf = kconfiglib.Kconfig()
  457. class KconfigParser:
  458. """A parser of .config and include/autoconf.mk."""
  459. re_arch = re.compile(r'CONFIG_SYS_ARCH="(.*)"')
  460. re_cpu = re.compile(r'CONFIG_SYS_CPU="(.*)"')
  461. def __init__(self, configs, args, build_dir):
  462. """Create a new parser.
  463. Args:
  464. configs: A list of CONFIGs to move.
  465. args (Namespace): program arguments
  466. build_dir: Build directory.
  467. """
  468. self.configs = configs
  469. self.args = args
  470. self.dotconfig = os.path.join(build_dir, '.config')
  471. self.autoconf = os.path.join(build_dir, 'include', 'autoconf.mk')
  472. self.spl_autoconf = os.path.join(build_dir, 'spl', 'include',
  473. 'autoconf.mk')
  474. self.config_autoconf = os.path.join(build_dir, AUTO_CONF_PATH)
  475. self.defconfig = os.path.join(build_dir, 'defconfig')
  476. def get_arch(self):
  477. """Parse .config file and return the architecture.
  478. Returns:
  479. Architecture name (e.g. 'arm').
  480. """
  481. arch = ''
  482. cpu = ''
  483. for line in read_file(self.dotconfig):
  484. m = self.re_arch.match(line)
  485. if m:
  486. arch = m.group(1)
  487. continue
  488. m = self.re_cpu.match(line)
  489. if m:
  490. cpu = m.group(1)
  491. if not arch:
  492. return None
  493. # fix-up for aarch64
  494. if arch == 'arm' and cpu == 'armv8':
  495. arch = 'aarch64'
  496. return arch
  497. def parse_one_config(self, config, dotconfig_lines, autoconf_lines):
  498. """Parse .config, defconfig, include/autoconf.mk for one config.
  499. This function looks for the config options in the lines from
  500. defconfig, .config, and include/autoconf.mk in order to decide
  501. which action should be taken for this defconfig.
  502. Args:
  503. config: CONFIG name to parse.
  504. dotconfig_lines: lines from the .config file.
  505. autoconf_lines: lines from the include/autoconf.mk file.
  506. Returns:
  507. A tupple of the action for this defconfig and the line
  508. matched for the config.
  509. """
  510. not_set = '# %s is not set' % config
  511. for line in autoconf_lines:
  512. line = line.rstrip()
  513. if line.startswith(config + '='):
  514. new_val = line
  515. break
  516. else:
  517. new_val = not_set
  518. new_val = try_expand(new_val)
  519. for line in dotconfig_lines:
  520. line = line.rstrip()
  521. if line.startswith(config + '=') or line == not_set:
  522. old_val = line
  523. break
  524. else:
  525. if new_val == not_set:
  526. return (ACTION_NO_ENTRY, config)
  527. else:
  528. return (ACTION_NO_ENTRY_WARN, config)
  529. # If this CONFIG is neither bool nor trisate
  530. if old_val[-2:] != '=y' and old_val[-2:] != '=m' and old_val != not_set:
  531. # tools/scripts/define2mk.sed changes '1' to 'y'.
  532. # This is a problem if the CONFIG is int type.
  533. # Check the type in Kconfig and handle it correctly.
  534. if new_val[-2:] == '=y':
  535. new_val = new_val[:-1] + '1'
  536. return (ACTION_NO_CHANGE if old_val == new_val else ACTION_MOVE,
  537. new_val)
  538. def update_dotconfig(self):
  539. """Parse files for the config options and update the .config.
  540. This function parses the generated .config and include/autoconf.mk
  541. searching the target options.
  542. Move the config option(s) to the .config as needed.
  543. Args:
  544. defconfig: defconfig name.
  545. Returns:
  546. Return a tuple of (updated flag, log string).
  547. The "updated flag" is True if the .config was updated, False
  548. otherwise. The "log string" shows what happend to the .config.
  549. """
  550. results = []
  551. updated = False
  552. suspicious = False
  553. rm_files = [self.config_autoconf, self.autoconf]
  554. if self.args.spl:
  555. if os.path.exists(self.spl_autoconf):
  556. autoconf_path = self.spl_autoconf
  557. rm_files.append(self.spl_autoconf)
  558. else:
  559. for f in rm_files:
  560. os.remove(f)
  561. return (updated, suspicious,
  562. color_text(self.args.color, COLOR_BROWN,
  563. "SPL is not enabled. Skipped.") + '\n')
  564. else:
  565. autoconf_path = self.autoconf
  566. dotconfig_lines = read_file(self.dotconfig)
  567. autoconf_lines = read_file(autoconf_path)
  568. for config in self.configs:
  569. result = self.parse_one_config(config, dotconfig_lines,
  570. autoconf_lines)
  571. results.append(result)
  572. log = ''
  573. for (action, value) in results:
  574. if action == ACTION_MOVE:
  575. actlog = "Move '%s'" % value
  576. log_color = COLOR_LIGHT_GREEN
  577. elif action == ACTION_NO_ENTRY:
  578. actlog = '%s is not defined in Kconfig. Do nothing.' % value
  579. log_color = COLOR_LIGHT_BLUE
  580. elif action == ACTION_NO_ENTRY_WARN:
  581. actlog = '%s is not defined in Kconfig (suspicious). Do nothing.' % value
  582. log_color = COLOR_YELLOW
  583. suspicious = True
  584. elif action == ACTION_NO_CHANGE:
  585. actlog = "'%s' is the same as the define in Kconfig. Do nothing." \
  586. % value
  587. log_color = COLOR_LIGHT_PURPLE
  588. else:
  589. sys.exit('Internal Error. This should not happen.')
  590. log += color_text(self.args.color, log_color, actlog) + '\n'
  591. with open(self.dotconfig, 'a', encoding='utf-8') as out:
  592. for (action, value) in results:
  593. if action == ACTION_MOVE:
  594. out.write(value + '\n')
  595. updated = True
  596. self.results = results
  597. for f in rm_files:
  598. os.remove(f)
  599. return (updated, suspicious, log)
  600. def check_defconfig(self):
  601. """Check the defconfig after savedefconfig
  602. Returns:
  603. Return additional log if moved CONFIGs were removed again by
  604. 'make savedefconfig'.
  605. """
  606. log = ''
  607. defconfig_lines = read_file(self.defconfig)
  608. for (action, value) in self.results:
  609. if action != ACTION_MOVE:
  610. continue
  611. if not value in defconfig_lines:
  612. log += color_text(self.args.color, COLOR_YELLOW,
  613. "'%s' was removed by savedefconfig.\n" %
  614. value)
  615. return log
  616. class DatabaseThread(threading.Thread):
  617. """This thread processes results from Slot threads.
  618. It collects the data in the master config directary. There is only one
  619. result thread, and this helps to serialise the build output.
  620. """
  621. def __init__(self, config_db, db_queue):
  622. """Set up a new result thread
  623. Args:
  624. builder: Builder which will be sent each result
  625. """
  626. threading.Thread.__init__(self)
  627. self.config_db = config_db
  628. self.db_queue= db_queue
  629. def run(self):
  630. """Called to start up the result thread.
  631. We collect the next result job and pass it on to the build.
  632. """
  633. while True:
  634. defconfig, configs = self.db_queue.get()
  635. self.config_db[defconfig] = configs
  636. self.db_queue.task_done()
  637. class Slot:
  638. """A slot to store a subprocess.
  639. Each instance of this class handles one subprocess.
  640. This class is useful to control multiple threads
  641. for faster processing.
  642. """
  643. def __init__(self, toolchains, configs, args, progress, devnull,
  644. make_cmd, reference_src_dir, db_queue):
  645. """Create a new process slot.
  646. Args:
  647. toolchains: Toolchains object containing toolchains.
  648. configs: A list of CONFIGs to move.
  649. args: Program arguments
  650. progress: A progress indicator.
  651. devnull: A file object of '/dev/null'.
  652. make_cmd: command name of GNU Make.
  653. reference_src_dir: Determine the true starting config state from this
  654. source tree.
  655. db_queue: output queue to write config info for the database
  656. """
  657. self.toolchains = toolchains
  658. self.args = args
  659. self.progress = progress
  660. self.build_dir = tempfile.mkdtemp()
  661. self.devnull = devnull
  662. self.make_cmd = (make_cmd, 'O=' + self.build_dir)
  663. self.reference_src_dir = reference_src_dir
  664. self.db_queue = db_queue
  665. self.parser = KconfigParser(configs, args, self.build_dir)
  666. self.state = STATE_IDLE
  667. self.failed_boards = set()
  668. self.suspicious_boards = set()
  669. def __del__(self):
  670. """Delete the working directory
  671. This function makes sure the temporary directory is cleaned away
  672. even if Python suddenly dies due to error. It should be done in here
  673. because it is guaranteed the destructor is always invoked when the
  674. instance of the class gets unreferenced.
  675. If the subprocess is still running, wait until it finishes.
  676. """
  677. if self.state != STATE_IDLE:
  678. while self.ps.poll() == None:
  679. pass
  680. shutil.rmtree(self.build_dir)
  681. def add(self, defconfig):
  682. """Assign a new subprocess for defconfig and add it to the slot.
  683. If the slot is vacant, create a new subprocess for processing the
  684. given defconfig and add it to the slot. Just returns False if
  685. the slot is occupied (i.e. the current subprocess is still running).
  686. Args:
  687. defconfig: defconfig name.
  688. Returns:
  689. Return True on success or False on failure
  690. """
  691. if self.state != STATE_IDLE:
  692. return False
  693. self.defconfig = defconfig
  694. self.log = ''
  695. self.current_src_dir = self.reference_src_dir
  696. self.do_defconfig()
  697. return True
  698. def poll(self):
  699. """Check the status of the subprocess and handle it as needed.
  700. Returns True if the slot is vacant (i.e. in idle state).
  701. If the configuration is successfully finished, assign a new
  702. subprocess to build include/autoconf.mk.
  703. If include/autoconf.mk is generated, invoke the parser to
  704. parse the .config and the include/autoconf.mk, moving
  705. config options to the .config as needed.
  706. If the .config was updated, run "make savedefconfig" to sync
  707. it, update the original defconfig, and then set the slot back
  708. to the idle state.
  709. Returns:
  710. Return True if the subprocess is terminated, False otherwise
  711. """
  712. if self.state == STATE_IDLE:
  713. return True
  714. if self.ps.poll() == None:
  715. return False
  716. if self.ps.poll() != 0:
  717. self.handle_error()
  718. elif self.state == STATE_DEFCONFIG:
  719. if self.reference_src_dir and not self.current_src_dir:
  720. self.do_savedefconfig()
  721. else:
  722. self.do_autoconf()
  723. elif self.state == STATE_AUTOCONF:
  724. if self.current_src_dir:
  725. self.current_src_dir = None
  726. self.do_defconfig()
  727. elif self.args.build_db:
  728. self.do_build_db()
  729. else:
  730. self.do_savedefconfig()
  731. elif self.state == STATE_SAVEDEFCONFIG:
  732. self.update_defconfig()
  733. else:
  734. sys.exit('Internal Error. This should not happen.')
  735. return True if self.state == STATE_IDLE else False
  736. def handle_error(self):
  737. """Handle error cases."""
  738. self.log += color_text(self.args.color, COLOR_LIGHT_RED,
  739. 'Failed to process.\n')
  740. if self.args.verbose:
  741. self.log += color_text(self.args.color, COLOR_LIGHT_CYAN,
  742. self.ps.stderr.read().decode())
  743. self.finish(False)
  744. def do_defconfig(self):
  745. """Run 'make <board>_defconfig' to create the .config file."""
  746. cmd = list(self.make_cmd)
  747. cmd.append(self.defconfig)
  748. self.ps = subprocess.Popen(cmd, stdout=self.devnull,
  749. stderr=subprocess.PIPE,
  750. cwd=self.current_src_dir)
  751. self.state = STATE_DEFCONFIG
  752. def do_autoconf(self):
  753. """Run 'make AUTO_CONF_PATH'."""
  754. arch = self.parser.get_arch()
  755. try:
  756. toolchain = self.toolchains.Select(arch)
  757. except ValueError:
  758. self.log += color_text(self.args.color, COLOR_YELLOW,
  759. "Tool chain for '%s' is missing. Do nothing.\n" % arch)
  760. self.finish(False)
  761. return
  762. env = toolchain.MakeEnvironment(False)
  763. cmd = list(self.make_cmd)
  764. cmd.append('KCONFIG_IGNORE_DUPLICATES=1')
  765. cmd.append(AUTO_CONF_PATH)
  766. self.ps = subprocess.Popen(cmd, stdout=self.devnull, env=env,
  767. stderr=subprocess.PIPE,
  768. cwd=self.current_src_dir)
  769. self.state = STATE_AUTOCONF
  770. def do_build_db(self):
  771. """Add the board to the database"""
  772. configs = {}
  773. for line in read_file(os.path.join(self.build_dir, AUTO_CONF_PATH)):
  774. if line.startswith('CONFIG'):
  775. config, value = line.split('=', 1)
  776. configs[config] = value.rstrip()
  777. self.db_queue.put([self.defconfig, configs])
  778. self.finish(True)
  779. def do_savedefconfig(self):
  780. """Update the .config and run 'make savedefconfig'."""
  781. (updated, suspicious, log) = self.parser.update_dotconfig()
  782. if suspicious:
  783. self.suspicious_boards.add(self.defconfig)
  784. self.log += log
  785. if not self.args.force_sync and not updated:
  786. self.finish(True)
  787. return
  788. if updated:
  789. self.log += color_text(self.args.color, COLOR_LIGHT_GREEN,
  790. 'Syncing by savedefconfig...\n')
  791. else:
  792. self.log += 'Syncing by savedefconfig (forced by option)...\n'
  793. cmd = list(self.make_cmd)
  794. cmd.append('savedefconfig')
  795. self.ps = subprocess.Popen(cmd, stdout=self.devnull,
  796. stderr=subprocess.PIPE)
  797. self.state = STATE_SAVEDEFCONFIG
  798. def update_defconfig(self):
  799. """Update the input defconfig and go back to the idle state."""
  800. log = self.parser.check_defconfig()
  801. if log:
  802. self.suspicious_boards.add(self.defconfig)
  803. self.log += log
  804. orig_defconfig = os.path.join('configs', self.defconfig)
  805. new_defconfig = os.path.join(self.build_dir, 'defconfig')
  806. updated = not filecmp.cmp(orig_defconfig, new_defconfig)
  807. if updated:
  808. self.log += color_text(self.args.color, COLOR_LIGHT_BLUE,
  809. 'defconfig was updated.\n')
  810. if not self.args.dry_run and updated:
  811. shutil.move(new_defconfig, orig_defconfig)
  812. self.finish(True)
  813. def finish(self, success):
  814. """Display log along with progress and go to the idle state.
  815. Args:
  816. success: Should be True when the defconfig was processed
  817. successfully, or False when it fails.
  818. """
  819. # output at least 30 characters to hide the "* defconfigs out of *".
  820. log = self.defconfig.ljust(30) + '\n'
  821. log += '\n'.join([ ' ' + s for s in self.log.split('\n') ])
  822. # Some threads are running in parallel.
  823. # Print log atomically to not mix up logs from different threads.
  824. print(log, file=(sys.stdout if success else sys.stderr))
  825. if not success:
  826. if self.args.exit_on_error:
  827. sys.exit('Exit on error.')
  828. # If --exit-on-error flag is not set, skip this board and continue.
  829. # Record the failed board.
  830. self.failed_boards.add(self.defconfig)
  831. self.progress.inc()
  832. self.progress.show()
  833. self.state = STATE_IDLE
  834. def get_failed_boards(self):
  835. """Returns a set of failed boards (defconfigs) in this slot.
  836. """
  837. return self.failed_boards
  838. def get_suspicious_boards(self):
  839. """Returns a set of boards (defconfigs) with possible misconversion.
  840. """
  841. return self.suspicious_boards - self.failed_boards
  842. class Slots:
  843. """Controller of the array of subprocess slots."""
  844. def __init__(self, toolchains, configs, args, progress,
  845. reference_src_dir, db_queue):
  846. """Create a new slots controller.
  847. Args:
  848. toolchains: Toolchains object containing toolchains.
  849. configs: A list of CONFIGs to move.
  850. args: Program arguments
  851. progress: A progress indicator.
  852. reference_src_dir: Determine the true starting config state from this
  853. source tree.
  854. db_queue: output queue to write config info for the database
  855. """
  856. self.args = args
  857. self.slots = []
  858. devnull = subprocess.DEVNULL
  859. make_cmd = get_make_cmd()
  860. for i in range(args.jobs):
  861. self.slots.append(Slot(toolchains, configs, args, progress,
  862. devnull, make_cmd, reference_src_dir,
  863. db_queue))
  864. def add(self, defconfig):
  865. """Add a new subprocess if a vacant slot is found.
  866. Args:
  867. defconfig: defconfig name to be put into.
  868. Returns:
  869. Return True on success or False on failure
  870. """
  871. for slot in self.slots:
  872. if slot.add(defconfig):
  873. return True
  874. return False
  875. def available(self):
  876. """Check if there is a vacant slot.
  877. Returns:
  878. Return True if at lease one vacant slot is found, False otherwise.
  879. """
  880. for slot in self.slots:
  881. if slot.poll():
  882. return True
  883. return False
  884. def empty(self):
  885. """Check if all slots are vacant.
  886. Returns:
  887. Return True if all the slots are vacant, False otherwise.
  888. """
  889. ret = True
  890. for slot in self.slots:
  891. if not slot.poll():
  892. ret = False
  893. return ret
  894. def show_failed_boards(self):
  895. """Display all of the failed boards (defconfigs)."""
  896. boards = set()
  897. output_file = 'moveconfig.failed'
  898. for slot in self.slots:
  899. boards |= slot.get_failed_boards()
  900. if boards:
  901. boards = '\n'.join(boards) + '\n'
  902. msg = 'The following boards were not processed due to error:\n'
  903. msg += boards
  904. msg += '(the list has been saved in %s)\n' % output_file
  905. print(color_text(self.args.color, COLOR_LIGHT_RED,
  906. msg), file=sys.stderr)
  907. write_file(output_file, boards)
  908. def show_suspicious_boards(self):
  909. """Display all boards (defconfigs) with possible misconversion."""
  910. boards = set()
  911. output_file = 'moveconfig.suspicious'
  912. for slot in self.slots:
  913. boards |= slot.get_suspicious_boards()
  914. if boards:
  915. boards = '\n'.join(boards) + '\n'
  916. msg = 'The following boards might have been converted incorrectly.\n'
  917. msg += 'It is highly recommended to check them manually:\n'
  918. msg += boards
  919. msg += '(the list has been saved in %s)\n' % output_file
  920. print(color_text(self.args.color, COLOR_YELLOW,
  921. msg), file=sys.stderr)
  922. write_file(output_file, boards)
  923. class ReferenceSource:
  924. """Reference source against which original configs should be parsed."""
  925. def __init__(self, commit):
  926. """Create a reference source directory based on a specified commit.
  927. Args:
  928. commit: commit to git-clone
  929. """
  930. self.src_dir = tempfile.mkdtemp()
  931. print('Cloning git repo to a separate work directory...')
  932. subprocess.check_output(['git', 'clone', os.getcwd(), '.'],
  933. cwd=self.src_dir)
  934. print("Checkout '%s' to build the original autoconf.mk." % \
  935. subprocess.check_output(['git', 'rev-parse', '--short', commit]).strip())
  936. subprocess.check_output(['git', 'checkout', commit],
  937. stderr=subprocess.STDOUT, cwd=self.src_dir)
  938. def __del__(self):
  939. """Delete the reference source directory
  940. This function makes sure the temporary directory is cleaned away
  941. even if Python suddenly dies due to error. It should be done in here
  942. because it is guaranteed the destructor is always invoked when the
  943. instance of the class gets unreferenced.
  944. """
  945. shutil.rmtree(self.src_dir)
  946. def get_dir(self):
  947. """Return the absolute path to the reference source directory."""
  948. return self.src_dir
  949. def move_config(toolchains, configs, args, db_queue):
  950. """Move config options to defconfig files.
  951. Args:
  952. configs: A list of CONFIGs to move.
  953. args: Program arguments
  954. """
  955. if len(configs) == 0:
  956. if args.force_sync:
  957. print('No CONFIG is specified. You are probably syncing defconfigs.', end=' ')
  958. elif args.build_db:
  959. print('Building %s database' % CONFIG_DATABASE)
  960. else:
  961. print('Neither CONFIG nor --force-sync is specified. Nothing will happen.', end=' ')
  962. else:
  963. print('Move ' + ', '.join(configs), end=' ')
  964. print('(jobs: %d)\n' % args.jobs)
  965. if args.git_ref:
  966. reference_src = ReferenceSource(args.git_ref)
  967. reference_src_dir = reference_src.get_dir()
  968. else:
  969. reference_src_dir = None
  970. if args.defconfigs:
  971. defconfigs = get_matched_defconfigs(args.defconfigs)
  972. else:
  973. defconfigs = get_all_defconfigs()
  974. progress = Progress(len(defconfigs))
  975. slots = Slots(toolchains, configs, args, progress, reference_src_dir,
  976. db_queue)
  977. # Main loop to process defconfig files:
  978. # Add a new subprocess into a vacant slot.
  979. # Sleep if there is no available slot.
  980. for defconfig in defconfigs:
  981. while not slots.add(defconfig):
  982. while not slots.available():
  983. # No available slot: sleep for a while
  984. time.sleep(SLEEP_TIME)
  985. # wait until all the subprocesses finish
  986. while not slots.empty():
  987. time.sleep(SLEEP_TIME)
  988. print('')
  989. slots.show_failed_boards()
  990. slots.show_suspicious_boards()
  991. def find_kconfig_rules(kconf, config, imply_config):
  992. """Check whether a config has a 'select' or 'imply' keyword
  993. Args:
  994. kconf: Kconfiglib.Kconfig object
  995. config: Name of config to check (without CONFIG_ prefix)
  996. imply_config: Implying config (without CONFIG_ prefix) which may or
  997. may not have an 'imply' for 'config')
  998. Returns:
  999. Symbol object for 'config' if found, else None
  1000. """
  1001. sym = kconf.syms.get(imply_config)
  1002. if sym:
  1003. for sel, cond in (sym.selects + sym.implies):
  1004. if sel.name == config:
  1005. return sym
  1006. return None
  1007. def check_imply_rule(kconf, config, imply_config):
  1008. """Check if we can add an 'imply' option
  1009. This finds imply_config in the Kconfig and looks to see if it is possible
  1010. to add an 'imply' for 'config' to that part of the Kconfig.
  1011. Args:
  1012. kconf: Kconfiglib.Kconfig object
  1013. config: Name of config to check (without CONFIG_ prefix)
  1014. imply_config: Implying config (without CONFIG_ prefix) which may or
  1015. may not have an 'imply' for 'config')
  1016. Returns:
  1017. tuple:
  1018. filename of Kconfig file containing imply_config, or None if none
  1019. line number within the Kconfig file, or 0 if none
  1020. message indicating the result
  1021. """
  1022. sym = kconf.syms.get(imply_config)
  1023. if not sym:
  1024. return 'cannot find sym'
  1025. nodes = sym.nodes
  1026. if len(nodes) != 1:
  1027. return '%d locations' % len(nodes)
  1028. node = nodes[0]
  1029. fname, linenum = node.filename, node.linenr
  1030. cwd = os.getcwd()
  1031. if cwd and fname.startswith(cwd):
  1032. fname = fname[len(cwd) + 1:]
  1033. file_line = ' at %s:%d' % (fname, linenum)
  1034. data = read_file(fname)
  1035. if data[linenum - 1] != 'config %s' % imply_config:
  1036. return None, 0, 'bad sym format %s%s' % (data[linenum], file_line)
  1037. return fname, linenum, 'adding%s' % file_line
  1038. def add_imply_rule(config, fname, linenum):
  1039. """Add a new 'imply' option to a Kconfig
  1040. Args:
  1041. config: config option to add an imply for (without CONFIG_ prefix)
  1042. fname: Kconfig filename to update
  1043. linenum: Line number to place the 'imply' before
  1044. Returns:
  1045. Message indicating the result
  1046. """
  1047. file_line = ' at %s:%d' % (fname, linenum)
  1048. data = read_file(fname)
  1049. linenum -= 1
  1050. for offset, line in enumerate(data[linenum:]):
  1051. if line.strip().startswith('help') or not line:
  1052. data.insert(linenum + offset, '\timply %s' % config)
  1053. write_file(fname, data)
  1054. return 'added%s' % file_line
  1055. return 'could not insert%s'
  1056. (IMPLY_MIN_2, IMPLY_TARGET, IMPLY_CMD, IMPLY_NON_ARCH_BOARD) = (
  1057. 1, 2, 4, 8)
  1058. IMPLY_FLAGS = {
  1059. 'min2': [IMPLY_MIN_2, 'Show options which imply >2 boards (normally >5)'],
  1060. 'target': [IMPLY_TARGET, 'Allow CONFIG_TARGET_... options to imply'],
  1061. 'cmd': [IMPLY_CMD, 'Allow CONFIG_CMD_... to imply'],
  1062. 'non-arch-board': [
  1063. IMPLY_NON_ARCH_BOARD,
  1064. 'Allow Kconfig options outside arch/ and /board/ to imply'],
  1065. }
  1066. def read_database():
  1067. """Read in the config database
  1068. Returns:
  1069. tuple:
  1070. set of all config options seen (each a str)
  1071. set of all defconfigs seen (each a str)
  1072. dict of configs for each defconfig:
  1073. key: defconfig name, e.g. "MPC8548CDS_legacy_defconfig"
  1074. value: dict:
  1075. key: CONFIG option
  1076. value: Value of option
  1077. dict of defconfigs for each config:
  1078. key: CONFIG option
  1079. value: set of boards using that option
  1080. """
  1081. configs = {}
  1082. # key is defconfig name, value is dict of (CONFIG_xxx, value)
  1083. config_db = {}
  1084. # Set of all config options we have seen
  1085. all_configs = set()
  1086. # Set of all defconfigs we have seen
  1087. all_defconfigs = set()
  1088. defconfig_db = collections.defaultdict(set)
  1089. for line in read_file(CONFIG_DATABASE):
  1090. line = line.rstrip()
  1091. if not line: # Separator between defconfigs
  1092. config_db[defconfig] = configs
  1093. all_defconfigs.add(defconfig)
  1094. configs = {}
  1095. elif line[0] == ' ': # CONFIG line
  1096. config, value = line.strip().split('=', 1)
  1097. configs[config] = value
  1098. defconfig_db[config].add(defconfig)
  1099. all_configs.add(config)
  1100. else: # New defconfig
  1101. defconfig = line
  1102. return all_configs, all_defconfigs, config_db, defconfig_db
  1103. def do_imply_config(config_list, add_imply, imply_flags, skip_added,
  1104. check_kconfig=True, find_superset=False):
  1105. """Find CONFIG options which imply those in the list
  1106. Some CONFIG options can be implied by others and this can help to reduce
  1107. the size of the defconfig files. For example, CONFIG_X86 implies
  1108. CONFIG_CMD_IRQ, so we can put 'imply CMD_IRQ' under 'config X86' and
  1109. all x86 boards will have that option, avoiding adding CONFIG_CMD_IRQ to
  1110. each of the x86 defconfig files.
  1111. This function uses the moveconfig database to find such options. It
  1112. displays a list of things that could possibly imply those in the list.
  1113. The algorithm ignores any that start with CONFIG_TARGET since these
  1114. typically refer to only a few defconfigs (often one). It also does not
  1115. display a config with less than 5 defconfigs.
  1116. The algorithm works using sets. For each target config in config_list:
  1117. - Get the set 'defconfigs' which use that target config
  1118. - For each config (from a list of all configs):
  1119. - Get the set 'imply_defconfig' of defconfigs which use that config
  1120. -
  1121. - If imply_defconfigs contains anything not in defconfigs then
  1122. this config does not imply the target config
  1123. Params:
  1124. config_list: List of CONFIG options to check (each a string)
  1125. add_imply: Automatically add an 'imply' for each config.
  1126. imply_flags: Flags which control which implying configs are allowed
  1127. (IMPLY_...)
  1128. skip_added: Don't show options which already have an imply added.
  1129. check_kconfig: Check if implied symbols already have an 'imply' or
  1130. 'select' for the target config, and show this information if so.
  1131. find_superset: True to look for configs which are a superset of those
  1132. already found. So for example if CONFIG_EXYNOS5 implies an option,
  1133. but CONFIG_EXYNOS covers a larger set of defconfigs and also
  1134. implies that option, this will drop the former in favour of the
  1135. latter. In practice this option has not proved very used.
  1136. Note the terminoloy:
  1137. config - a CONFIG_XXX options (a string, e.g. 'CONFIG_CMD_EEPROM')
  1138. defconfig - a defconfig file (a string, e.g. 'configs/snow_defconfig')
  1139. """
  1140. kconf = KconfigScanner().conf if check_kconfig else None
  1141. if add_imply and add_imply != 'all':
  1142. add_imply = add_imply.split(',')
  1143. all_configs, all_defconfigs, config_db, defconfig_db = read_database()
  1144. # Work through each target config option in turn, independently
  1145. for config in config_list:
  1146. defconfigs = defconfig_db.get(config)
  1147. if not defconfigs:
  1148. print('%s not found in any defconfig' % config)
  1149. continue
  1150. # Get the set of defconfigs without this one (since a config cannot
  1151. # imply itself)
  1152. non_defconfigs = all_defconfigs - defconfigs
  1153. num_defconfigs = len(defconfigs)
  1154. print('%s found in %d/%d defconfigs' % (config, num_defconfigs,
  1155. len(all_configs)))
  1156. # This will hold the results: key=config, value=defconfigs containing it
  1157. imply_configs = {}
  1158. rest_configs = all_configs - set([config])
  1159. # Look at every possible config, except the target one
  1160. for imply_config in rest_configs:
  1161. if 'ERRATUM' in imply_config:
  1162. continue
  1163. if not imply_flags & IMPLY_CMD:
  1164. if 'CONFIG_CMD' in imply_config:
  1165. continue
  1166. if not imply_flags & IMPLY_TARGET:
  1167. if 'CONFIG_TARGET' in imply_config:
  1168. continue
  1169. # Find set of defconfigs that have this config
  1170. imply_defconfig = defconfig_db[imply_config]
  1171. # Get the intersection of this with defconfigs containing the
  1172. # target config
  1173. common_defconfigs = imply_defconfig & defconfigs
  1174. # Get the set of defconfigs containing this config which DO NOT
  1175. # also contain the taret config. If this set is non-empty it means
  1176. # that this config affects other defconfigs as well as (possibly)
  1177. # the ones affected by the target config. This means it implies
  1178. # things we don't want to imply.
  1179. not_common_defconfigs = imply_defconfig & non_defconfigs
  1180. if not_common_defconfigs:
  1181. continue
  1182. # If there are common defconfigs, imply_config may be useful
  1183. if common_defconfigs:
  1184. skip = False
  1185. if find_superset:
  1186. for prev in list(imply_configs.keys()):
  1187. prev_count = len(imply_configs[prev])
  1188. count = len(common_defconfigs)
  1189. if (prev_count > count and
  1190. (imply_configs[prev] & common_defconfigs ==
  1191. common_defconfigs)):
  1192. # skip imply_config because prev is a superset
  1193. skip = True
  1194. break
  1195. elif count > prev_count:
  1196. # delete prev because imply_config is a superset
  1197. del imply_configs[prev]
  1198. if not skip:
  1199. imply_configs[imply_config] = common_defconfigs
  1200. # Now we have a dict imply_configs of configs which imply each config
  1201. # The value of each dict item is the set of defconfigs containing that
  1202. # config. Rank them so that we print the configs that imply the largest
  1203. # number of defconfigs first.
  1204. ranked_iconfigs = sorted(imply_configs,
  1205. key=lambda k: len(imply_configs[k]), reverse=True)
  1206. kconfig_info = ''
  1207. cwd = os.getcwd()
  1208. add_list = collections.defaultdict(list)
  1209. for iconfig in ranked_iconfigs:
  1210. num_common = len(imply_configs[iconfig])
  1211. # Don't bother if there are less than 5 defconfigs affected.
  1212. if num_common < (2 if imply_flags & IMPLY_MIN_2 else 5):
  1213. continue
  1214. missing = defconfigs - imply_configs[iconfig]
  1215. missing_str = ', '.join(missing) if missing else 'all'
  1216. missing_str = ''
  1217. show = True
  1218. if kconf:
  1219. sym = find_kconfig_rules(kconf, config[CONFIG_LEN:],
  1220. iconfig[CONFIG_LEN:])
  1221. kconfig_info = ''
  1222. if sym:
  1223. nodes = sym.nodes
  1224. if len(nodes) == 1:
  1225. fname, linenum = nodes[0].filename, nodes[0].linenr
  1226. if cwd and fname.startswith(cwd):
  1227. fname = fname[len(cwd) + 1:]
  1228. kconfig_info = '%s:%d' % (fname, linenum)
  1229. if skip_added:
  1230. show = False
  1231. else:
  1232. sym = kconf.syms.get(iconfig[CONFIG_LEN:])
  1233. fname = ''
  1234. if sym:
  1235. nodes = sym.nodes
  1236. if len(nodes) == 1:
  1237. fname, linenum = nodes[0].filename, nodes[0].linenr
  1238. if cwd and fname.startswith(cwd):
  1239. fname = fname[len(cwd) + 1:]
  1240. in_arch_board = not sym or (fname.startswith('arch') or
  1241. fname.startswith('board'))
  1242. if (not in_arch_board and
  1243. not imply_flags & IMPLY_NON_ARCH_BOARD):
  1244. continue
  1245. if add_imply and (add_imply == 'all' or
  1246. iconfig in add_imply):
  1247. fname, linenum, kconfig_info = (check_imply_rule(kconf,
  1248. config[CONFIG_LEN:], iconfig[CONFIG_LEN:]))
  1249. if fname:
  1250. add_list[fname].append(linenum)
  1251. if show and kconfig_info != 'skip':
  1252. print('%5d : %-30s%-25s %s' % (num_common, iconfig.ljust(30),
  1253. kconfig_info, missing_str))
  1254. # Having collected a list of things to add, now we add them. We process
  1255. # each file from the largest line number to the smallest so that
  1256. # earlier additions do not affect our line numbers. E.g. if we added an
  1257. # imply at line 20 it would change the position of each line after
  1258. # that.
  1259. for fname, linenums in add_list.items():
  1260. for linenum in sorted(linenums, reverse=True):
  1261. add_imply_rule(config[CONFIG_LEN:], fname, linenum)
  1262. def defconfig_matches(configs, re_match):
  1263. """Check if any CONFIG option matches a regex
  1264. The match must be complete, i.e. from the start to end of the CONFIG option.
  1265. Args:
  1266. configs (dict): Dict of CONFIG options:
  1267. key: CONFIG option
  1268. value: Value of option
  1269. re_match (re.Pattern): Match to check
  1270. Returns:
  1271. bool: True if any CONFIG matches the regex
  1272. """
  1273. for cfg in configs:
  1274. if re_match.fullmatch(cfg):
  1275. return True
  1276. return False
  1277. def do_find_config(config_list):
  1278. """Find boards with a given combination of CONFIGs
  1279. Params:
  1280. config_list: List of CONFIG options to check (each a regex consisting
  1281. of a config option, with or without a CONFIG_ prefix. If an option
  1282. is preceded by a tilde (~) then it must be false, otherwise it must
  1283. be true)
  1284. """
  1285. all_configs, all_defconfigs, config_db, defconfig_db = read_database()
  1286. # Start with all defconfigs
  1287. out = all_defconfigs
  1288. # Work through each config in turn
  1289. for item in config_list:
  1290. # Get the real config name and whether we want this config or not
  1291. cfg = item
  1292. want = True
  1293. if cfg[0] == '~':
  1294. want = False
  1295. cfg = cfg[1:]
  1296. # Search everything that is still in the running. If it has a config
  1297. # that we want, or doesn't have one that we don't, add it into the
  1298. # running for the next stage
  1299. in_list = out
  1300. out = set()
  1301. re_match = re.compile(cfg)
  1302. for defc in in_list:
  1303. has_cfg = defconfig_matches(config_db[defc], re_match)
  1304. if has_cfg == want:
  1305. out.add(defc)
  1306. print(f'{len(out)} matches')
  1307. print(' '.join(item.split('_defconfig')[0] for item in out))
  1308. def prefix_config(cfg):
  1309. """Prefix a config with CONFIG_ if needed
  1310. This handles ~ operator, which indicates that the CONFIG should be disabled
  1311. >>> prefix_config('FRED')
  1312. 'CONFIG_FRED'
  1313. >>> prefix_config('CONFIG_FRED')
  1314. 'CONFIG_FRED'
  1315. >>> prefix_config('~FRED')
  1316. '~CONFIG_FRED'
  1317. >>> prefix_config('~CONFIG_FRED')
  1318. '~CONFIG_FRED'
  1319. >>> prefix_config('A123')
  1320. 'CONFIG_A123'
  1321. """
  1322. op = ''
  1323. if cfg[0] == '~':
  1324. op = cfg[0]
  1325. cfg = cfg[1:]
  1326. if not cfg.startswith('CONFIG_'):
  1327. cfg = 'CONFIG_' + cfg
  1328. return op + cfg
  1329. RE_MK_CONFIGS = re.compile('CONFIG_(\$\(SPL_(?:TPL_)?\))?([A-Za-z0-9_]*)')
  1330. RE_IFDEF = re.compile('(ifdef|ifndef)')
  1331. RE_C_CONFIGS = re.compile('CONFIG_([A-Za-z0-9_]*)')
  1332. RE_CONFIG_IS = re.compile('CONFIG_IS_ENABLED\(([A-Za-z0-9_]*)\)')
  1333. class ConfigUse:
  1334. def __init__(self, cfg, is_spl, fname, rest):
  1335. self.cfg = cfg
  1336. self.is_spl = is_spl
  1337. self.fname = fname
  1338. self.rest = rest
  1339. def __hash__(self):
  1340. return hash((self.cfg, self.is_spl))
  1341. def scan_makefiles(fnames):
  1342. """Scan Makefiles looking for Kconfig options
  1343. Looks for uses of CONFIG options in Makefiles
  1344. Args:
  1345. fnames (list of tuple):
  1346. str: Makefile filename where the option was found
  1347. str: Line of the Makefile
  1348. Returns:
  1349. tuple:
  1350. dict: all_uses
  1351. key (ConfigUse): object
  1352. value (list of str): matching lines
  1353. dict: Uses by filename
  1354. key (str): filename
  1355. value (set of ConfigUse): uses in that filename
  1356. >>> RE_MK_CONFIGS.search('CONFIG_FRED').groups()
  1357. (None, 'FRED')
  1358. >>> RE_MK_CONFIGS.search('CONFIG_$(SPL_)MARY').groups()
  1359. ('$(SPL_)', 'MARY')
  1360. >>> RE_MK_CONFIGS.search('CONFIG_$(SPL_TPL_)MARY').groups()
  1361. ('$(SPL_TPL_)', 'MARY')
  1362. """
  1363. all_uses = collections.defaultdict(list)
  1364. fname_uses = {}
  1365. for fname, rest in fnames:
  1366. m_iter = RE_MK_CONFIGS.finditer(rest)
  1367. found = False
  1368. for m in m_iter:
  1369. found = True
  1370. real_opt = m.group(2)
  1371. if real_opt == '':
  1372. continue
  1373. is_spl = False
  1374. if m.group(1):
  1375. is_spl = True
  1376. use = ConfigUse(real_opt, is_spl, fname, rest)
  1377. if fname not in fname_uses:
  1378. fname_uses[fname] = set()
  1379. fname_uses[fname].add(use)
  1380. all_uses[use].append(rest)
  1381. return all_uses, fname_uses
  1382. def scan_src_files(fnames):
  1383. """Scan source files (other than Makefiles) looking for Kconfig options
  1384. Looks for uses of CONFIG options
  1385. Args:
  1386. fnames (list of tuple):
  1387. str: Makefile filename where the option was found
  1388. str: Line of the Makefile
  1389. Returns:
  1390. tuple:
  1391. dict: all_uses
  1392. key (ConfigUse): object
  1393. value (list of str): matching lines
  1394. dict: Uses by filename
  1395. key (str): filename
  1396. value (set of ConfigUse): uses in that filename
  1397. >>> RE_C_CONFIGS.search('CONFIG_FRED').groups()
  1398. ('FRED',)
  1399. >>> RE_CONFIG_IS.search('CONFIG_IS_ENABLED(MARY)').groups()
  1400. ('MARY',)
  1401. >>> RE_CONFIG_IS.search('#if CONFIG_IS_ENABLED(OF_PLATDATA)').groups()
  1402. ('OF_PLATDATA',)
  1403. """
  1404. def add_uses(m_iter, is_spl):
  1405. for m in m_iter:
  1406. found = True
  1407. real_opt = m.group(1)
  1408. if real_opt == '':
  1409. continue
  1410. use = ConfigUse(real_opt, is_spl, fname, rest)
  1411. if fname not in fname_uses:
  1412. fname_uses[fname] = set()
  1413. fname_uses[fname].add(use)
  1414. all_uses[use].append(rest)
  1415. all_uses = collections.defaultdict(list)
  1416. fname_uses = {}
  1417. for fname, rest in fnames:
  1418. m_iter = RE_C_CONFIGS.finditer(rest)
  1419. add_uses(m_iter, False)
  1420. m_iter2 = RE_CONFIG_IS.finditer(rest)
  1421. add_uses(m_iter2, True)
  1422. return all_uses, fname_uses
  1423. MODE_NORMAL, MODE_SPL, MODE_PROPER = range(3)
  1424. def do_scan_source(path, do_update):
  1425. """Scan the source tree for Kconfig inconsistencies
  1426. Args:
  1427. path (str): Path to source tree
  1428. do_update (bool) : True to write to scripts/kconf_... files
  1429. """
  1430. def is_not_proper(name):
  1431. for prefix in SPL_PREFIXES:
  1432. if name.startswith(prefix):
  1433. return name[len(prefix):]
  1434. return False
  1435. def check_not_found(all_uses, spl_mode):
  1436. """Check for Kconfig options mentioned in the source but not in Kconfig
  1437. Args:
  1438. all_uses (dict):
  1439. key (ConfigUse): object
  1440. value (list of str): matching lines
  1441. spl_mode (int): If MODE_SPL, look at source code which implies
  1442. an SPL_ option, but for which there is none;
  1443. for MOD_PROPER, look at source code which implies a Proper
  1444. option (i.e. use of CONFIG_IS_ENABLED() or $(SPL_) or
  1445. $(SPL_TPL_) but for which there none;
  1446. if MODE_NORMAL, ignore SPL
  1447. Returns:
  1448. dict:
  1449. key (str): CONFIG name (without 'CONFIG_' prefix
  1450. value (list of ConfigUse): List of uses of this CONFIG
  1451. """
  1452. # Make sure we know about all the options
  1453. not_found = collections.defaultdict(list)
  1454. for use, rest in all_uses.items():
  1455. name = use.cfg
  1456. if name in IGNORE_SYMS:
  1457. continue
  1458. check = True
  1459. if spl_mode == MODE_SPL:
  1460. check = use.is_spl
  1461. # If it is an SPL symbol, try prepending all SPL_ prefixes to
  1462. # find at least one SPL symbol
  1463. if use.is_spl:
  1464. add_to_dict = False
  1465. for prefix in SPL_PREFIXES:
  1466. try_name = prefix + name
  1467. sym = kconf.syms.get(try_name)
  1468. if sym:
  1469. break
  1470. if not sym:
  1471. not_found[f'SPL_{name}'].append(use)
  1472. continue
  1473. elif spl_mode == MODE_PROPER:
  1474. # Try to find the Proper version of this symbol, i.e. without
  1475. # the SPL_ prefix
  1476. proper_name = is_not_proper(name)
  1477. if proper_name:
  1478. name = proper_name
  1479. elif not use.is_spl:
  1480. check = False
  1481. else: # MODE_NORMAL
  1482. debug = False
  1483. sym = kconf.syms.get(name)
  1484. if not sym:
  1485. proper_name = is_not_proper(name)
  1486. if proper_name:
  1487. name = proper_name
  1488. sym = kconf.syms.get(name)
  1489. if not sym:
  1490. for prefix in SPL_PREFIXES:
  1491. try_name = prefix + name
  1492. sym = kconf.syms.get(try_name)
  1493. if sym:
  1494. break
  1495. if not sym:
  1496. not_found[name].append(use)
  1497. continue
  1498. sym = kconf.syms.get(name)
  1499. if not sym and check:
  1500. not_found[name].append(use)
  1501. return not_found
  1502. def show_uses(uses):
  1503. """Show a list of uses along with their filename and code snippet
  1504. Args:
  1505. uses (dict):
  1506. key (str): CONFIG name (without 'CONFIG_' prefix
  1507. value (list of ConfigUse): List of uses of this CONFIG
  1508. """
  1509. for name in sorted(uses):
  1510. print(f'{name}: ', end='')
  1511. for i, use in enumerate(uses[name]):
  1512. print(f'{" " if i else ""}{use.fname}: {use.rest.strip()}')
  1513. print('Scanning Kconfig')
  1514. kconf = KconfigScanner().conf
  1515. print(f'Scanning source in {path}')
  1516. args = ['git', 'grep', '-E', r'IS_ENABLED|\bCONFIG']
  1517. with subprocess.Popen(args, stdout=subprocess.PIPE) as proc:
  1518. out, err = proc.communicate()
  1519. lines = out.splitlines()
  1520. re_fname = re.compile('^([^:]*):(.*)')
  1521. src_list = []
  1522. mk_list = []
  1523. for line in lines:
  1524. linestr = line.decode('utf-8')
  1525. m_fname = re_fname.search(linestr)
  1526. if not m_fname:
  1527. continue
  1528. fname, rest = m_fname.groups()
  1529. dirname, leaf = os.path.split(fname)
  1530. root, ext = os.path.splitext(leaf)
  1531. if ext == '.autoconf':
  1532. pass
  1533. elif ext in ['.c', '.h', '.S', '.lds', '.dts', '.dtsi', '.asl', '.cfg',
  1534. '.env', '.tmpl']:
  1535. src_list.append([fname, rest])
  1536. elif 'Makefile' in root or ext == '.mk':
  1537. mk_list.append([fname, rest])
  1538. elif ext in ['.yml', '.sh', '.py', '.awk', '.pl', '.rst', '', '.sed']:
  1539. pass
  1540. elif 'Kconfig' in root or 'Kbuild' in root:
  1541. pass
  1542. elif 'README' in root:
  1543. pass
  1544. elif dirname in ['configs']:
  1545. pass
  1546. elif dirname.startswith('doc') or dirname.startswith('scripts/kconfig'):
  1547. pass
  1548. else:
  1549. print(f'Not sure how to handle file {fname}')
  1550. # Scan the Makefiles
  1551. all_uses, fname_uses = scan_makefiles(mk_list)
  1552. spl_not_found = set()
  1553. proper_not_found = set()
  1554. # Make sure we know about all the options
  1555. print('\nCONFIG options present in Makefiles but not Kconfig:')
  1556. not_found = check_not_found(all_uses, MODE_NORMAL)
  1557. show_uses(not_found)
  1558. print('\nCONFIG options present in Makefiles but not Kconfig (SPL):')
  1559. not_found = check_not_found(all_uses, MODE_SPL)
  1560. show_uses(not_found)
  1561. spl_not_found |= set([is_not_proper(key) or key for key in not_found.keys()])
  1562. print('\nCONFIG options used as Proper in Makefiles but without a non-SPL_ variant:')
  1563. not_found = check_not_found(all_uses, MODE_PROPER)
  1564. show_uses(not_found)
  1565. proper_not_found |= set([key for key in not_found.keys()])
  1566. # Scan the source code
  1567. all_uses, fname_uses = scan_src_files(src_list)
  1568. # Make sure we know about all the options
  1569. print('\nCONFIG options present in source but not Kconfig:')
  1570. not_found = check_not_found(all_uses, MODE_NORMAL)
  1571. show_uses(not_found)
  1572. print('\nCONFIG options present in source but not Kconfig (SPL):')
  1573. not_found = check_not_found(all_uses, MODE_SPL)
  1574. show_uses(not_found)
  1575. spl_not_found |= set([is_not_proper(key) or key for key in not_found.keys()])
  1576. print('\nCONFIG options used as Proper in source but without a non-SPL_ variant:')
  1577. not_found = check_not_found(all_uses, MODE_PROPER)
  1578. show_uses(not_found)
  1579. proper_not_found |= set([key for key in not_found.keys()])
  1580. print('\nCONFIG options used as SPL but without an SPL_ variant:')
  1581. for item in sorted(spl_not_found):
  1582. print(f' {item}')
  1583. print('\nCONFIG options used as Proper but without a non-SPL_ variant:')
  1584. for item in sorted(proper_not_found):
  1585. print(f' {item}')
  1586. # Write out the updated information
  1587. if do_update:
  1588. with open(os.path.join(path, 'scripts', 'conf_nospl'), 'w') as out:
  1589. print('# These options should not be enabled in SPL builds\n',
  1590. file=out)
  1591. for item in sorted(spl_not_found):
  1592. print(item, file=out)
  1593. with open(os.path.join(path, 'scripts', 'conf_noproper'), 'w') as out:
  1594. print('# These options should not be enabled in Proper builds\n',
  1595. file=out)
  1596. for item in sorted(proper_not_found):
  1597. print(item, file=out)
  1598. def main():
  1599. try:
  1600. cpu_count = multiprocessing.cpu_count()
  1601. except NotImplementedError:
  1602. cpu_count = 1
  1603. epilog = '''Move config options from headers to defconfig files. See
  1604. doc/develop/moveconfig.rst for documentation.'''
  1605. parser = ArgumentParser(epilog=epilog)
  1606. # Add arguments here
  1607. parser.add_argument('-a', '--add-imply', type=str, default='',
  1608. help='comma-separated list of CONFIG options to add '
  1609. "an 'imply' statement to for the CONFIG in -i")
  1610. parser.add_argument('-A', '--skip-added', action='store_true', default=False,
  1611. help="don't show options which are already marked as "
  1612. 'implying others')
  1613. parser.add_argument('-b', '--build-db', action='store_true', default=False,
  1614. help='build a CONFIG database')
  1615. parser.add_argument('-c', '--color', action='store_true', default=False,
  1616. help='display the log in color')
  1617. parser.add_argument('-C', '--commit', action='store_true', default=False,
  1618. help='Create a git commit for the operation')
  1619. parser.add_argument('-d', '--defconfigs', type=str,
  1620. help='a file containing a list of defconfigs to move, '
  1621. "one per line (for example 'snow_defconfig') "
  1622. "or '-' to read from stdin")
  1623. parser.add_argument('-e', '--exit-on-error', action='store_true',
  1624. default=False,
  1625. help='exit immediately on any error')
  1626. parser.add_argument('-f', '--find', action='store_true', default=False,
  1627. help='Find boards with a given config combination')
  1628. parser.add_argument('-H', '--headers-only', dest='cleanup_headers_only',
  1629. action='store_true', default=False,
  1630. help='only cleanup the headers')
  1631. parser.add_argument('-i', '--imply', action='store_true', default=False,
  1632. help='find options which imply others')
  1633. parser.add_argument('-I', '--imply-flags', type=str, default='',
  1634. help="control the -i option ('help' for help")
  1635. parser.add_argument('-j', '--jobs', type=int, default=cpu_count,
  1636. help='the number of jobs to run simultaneously')
  1637. parser.add_argument('-n', '--dry-run', action='store_true', default=False,
  1638. help='perform a trial run (show log with no changes)')
  1639. parser.add_argument('-r', '--git-ref', type=str,
  1640. help='the git ref to clone for building the autoconf.mk')
  1641. parser.add_argument('-s', '--force-sync', action='store_true', default=False,
  1642. help='force sync by savedefconfig')
  1643. parser.add_argument('-S', '--spl', action='store_true', default=False,
  1644. help='parse config options defined for SPL build')
  1645. parser.add_argument('--scan-source', action='store_true', default=False,
  1646. help='scan source for uses of CONFIG options')
  1647. parser.add_argument('-t', '--test', action='store_true', default=False,
  1648. help='run unit tests')
  1649. parser.add_argument('-y', '--yes', action='store_true', default=False,
  1650. help="respond 'yes' to any prompts")
  1651. parser.add_argument('-u', '--update', action='store_true', default=False,
  1652. help="update scripts/ files (use with --scan-source)")
  1653. parser.add_argument('-v', '--verbose', action='store_true', default=False,
  1654. help='show any build errors as boards are built')
  1655. parser.add_argument('configs', nargs='*')
  1656. args = parser.parse_args()
  1657. configs = args.configs
  1658. if args.test:
  1659. sys.argv = [sys.argv[0]]
  1660. fail, count = doctest.testmod()
  1661. if fail:
  1662. return 1
  1663. unittest.main()
  1664. if args.scan_source:
  1665. do_scan_source(os.getcwd(), args.update)
  1666. return
  1667. if not any((len(configs), args.force_sync, args.build_db, args.imply,
  1668. args.find)):
  1669. parser.print_usage()
  1670. sys.exit(1)
  1671. # prefix the option name with CONFIG_ if missing
  1672. configs = [prefix_config(cfg) for cfg in configs]
  1673. check_top_directory()
  1674. if args.imply:
  1675. imply_flags = 0
  1676. if args.imply_flags == 'all':
  1677. imply_flags = -1
  1678. elif args.imply_flags:
  1679. for flag in args.imply_flags.split(','):
  1680. bad = flag not in IMPLY_FLAGS
  1681. if bad:
  1682. print("Invalid flag '%s'" % flag)
  1683. if flag == 'help' or bad:
  1684. print("Imply flags: (separate with ',')")
  1685. for name, info in IMPLY_FLAGS.items():
  1686. print(' %-15s: %s' % (name, info[1]))
  1687. parser.print_usage()
  1688. sys.exit(1)
  1689. imply_flags |= IMPLY_FLAGS[flag][0]
  1690. do_imply_config(configs, args.add_imply, imply_flags, args.skip_added)
  1691. return
  1692. if args.find:
  1693. do_find_config(configs)
  1694. return
  1695. config_db = {}
  1696. db_queue = queue.Queue()
  1697. t = DatabaseThread(config_db, db_queue)
  1698. t.setDaemon(True)
  1699. t.start()
  1700. if not args.cleanup_headers_only:
  1701. check_clean_directory()
  1702. bsettings.setup('')
  1703. toolchains = toolchain.Toolchains()
  1704. toolchains.GetSettings()
  1705. toolchains.Scan(verbose=False)
  1706. move_config(toolchains, configs, args, db_queue)
  1707. db_queue.join()
  1708. if configs:
  1709. cleanup_headers(configs, args)
  1710. cleanup_readme(configs, args)
  1711. if args.commit:
  1712. subprocess.call(['git', 'add', '-u'])
  1713. if configs:
  1714. msg = 'Convert %s %sto Kconfig' % (configs[0],
  1715. 'et al ' if len(configs) > 1 else '')
  1716. msg += ('\n\nThis converts the following to Kconfig:\n %s\n' %
  1717. '\n '.join(configs))
  1718. else:
  1719. msg = 'configs: Resync with savedefconfig'
  1720. msg += '\n\nRsync all defconfig files using moveconfig.py'
  1721. subprocess.call(['git', 'commit', '-s', '-m', msg])
  1722. if args.build_db:
  1723. with open(CONFIG_DATABASE, 'w', encoding='utf-8') as fd:
  1724. for defconfig, configs in config_db.items():
  1725. fd.write('%s\n' % defconfig)
  1726. for config in sorted(configs.keys()):
  1727. fd.write(' %s=%s\n' % (config, configs[config]))
  1728. fd.write('\n')
  1729. if __name__ == '__main__':
  1730. sys.exit(main())