moveconfig.py 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886
  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. This tool uses
  82. the same tools as buildman, so see that tool for setup (e.g. --fetch-arch).
  83. Tips and trips
  84. --------------
  85. To sync only X86 defconfigs:
  86. ./tools/moveconfig.py -s -d <(grep -l X86 configs/*)
  87. or:
  88. grep -l X86 configs/* | ./tools/moveconfig.py -s -d -
  89. To process CONFIG_CMD_FPGAD only for a subset of configs based on path match:
  90. ls configs/{hrcon*,iocon*,strider*} | \
  91. ./tools/moveconfig.py -Cy CONFIG_CMD_FPGAD -d -
  92. Finding implied CONFIGs
  93. -----------------------
  94. Some CONFIG options can be implied by others and this can help to reduce
  95. the size of the defconfig files. For example, CONFIG_X86 implies
  96. CONFIG_CMD_IRQ, so we can put 'imply CMD_IRQ' under 'config X86' and
  97. all x86 boards will have that option, avoiding adding CONFIG_CMD_IRQ to
  98. each of the x86 defconfig files.
  99. This tool can help find such configs. To use it, first build a database:
  100. ./tools/moveconfig.py -b
  101. Then try to query it:
  102. ./tools/moveconfig.py -i CONFIG_CMD_IRQ
  103. CONFIG_CMD_IRQ found in 311/2384 defconfigs
  104. 44 : CONFIG_SYS_FSL_ERRATUM_IFC_A002769
  105. 41 : CONFIG_SYS_FSL_ERRATUM_A007075
  106. 31 : CONFIG_SYS_FSL_DDR_VER_44
  107. 28 : CONFIG_ARCH_P1010
  108. 28 : CONFIG_SYS_FSL_ERRATUM_P1010_A003549
  109. 28 : CONFIG_SYS_FSL_ERRATUM_SEC_A003571
  110. 28 : CONFIG_SYS_FSL_ERRATUM_IFC_A003399
  111. 25 : CONFIG_SYS_FSL_ERRATUM_A008044
  112. 22 : CONFIG_ARCH_P1020
  113. 21 : CONFIG_SYS_FSL_DDR_VER_46
  114. 20 : CONFIG_MAX_PIRQ_LINKS
  115. 20 : CONFIG_HPET_ADDRESS
  116. 20 : CONFIG_X86
  117. 20 : CONFIG_PCIE_ECAM_SIZE
  118. 20 : CONFIG_IRQ_SLOT_COUNT
  119. 20 : CONFIG_I8259_PIC
  120. 20 : CONFIG_CPU_ADDR_BITS
  121. 20 : CONFIG_RAMBASE
  122. 20 : CONFIG_SYS_FSL_ERRATUM_A005871
  123. 20 : CONFIG_PCIE_ECAM_BASE
  124. 20 : CONFIG_X86_TSC_TIMER
  125. 20 : CONFIG_I8254_TIMER
  126. 20 : CONFIG_CMD_GETTIME
  127. 19 : CONFIG_SYS_FSL_ERRATUM_A005812
  128. 18 : CONFIG_X86_RUN_32BIT
  129. 17 : CONFIG_CMD_CHIP_CONFIG
  130. ...
  131. This shows a list of config options which might imply CONFIG_CMD_EEPROM along
  132. with how many defconfigs they cover. From this you can see that CONFIG_X86
  133. implies CONFIG_CMD_EEPROM. Therefore, instead of adding CONFIG_CMD_EEPROM to
  134. the defconfig of every x86 board, you could add a single imply line to the
  135. Kconfig file:
  136. config X86
  137. bool "x86 architecture"
  138. ...
  139. imply CMD_EEPROM
  140. That will cover 20 defconfigs. Many of the options listed are not suitable as
  141. they are not related. E.g. it would be odd for CONFIG_CMD_GETTIME to imply
  142. CMD_EEPROM.
  143. Using this search you can reduce the size of moveconfig patches.
  144. You can automatically add 'imply' statements in the Kconfig with the -a
  145. option:
  146. ./tools/moveconfig.py -s -i CONFIG_SCSI \
  147. -a CONFIG_ARCH_LS1021A,CONFIG_ARCH_LS1043A
  148. This will add 'imply SCSI' to the two CONFIG options mentioned, assuming that
  149. the database indicates that they do actually imply CONFIG_SCSI and do not
  150. already have an 'imply SCSI'.
  151. The output shows where the imply is added:
  152. 18 : CONFIG_ARCH_LS1021A arch/arm/cpu/armv7/ls102xa/Kconfig:1
  153. 13 : CONFIG_ARCH_LS1043A arch/arm/cpu/armv8/fsl-layerscape/Kconfig:11
  154. 12 : CONFIG_ARCH_LS1046A arch/arm/cpu/armv8/fsl-layerscape/Kconfig:31
  155. The first number is the number of boards which can avoid having a special
  156. CONFIG_SCSI option in their defconfig file if this 'imply' is added.
  157. The location at the right is the Kconfig file and line number where the config
  158. appears. For example, adding 'imply CONFIG_SCSI' to the 'config ARCH_LS1021A'
  159. in arch/arm/cpu/armv7/ls102xa/Kconfig at line 1 will help 18 boards to reduce
  160. the size of their defconfig files.
  161. If you want to add an 'imply' to every imply config in the list, you can use
  162. ./tools/moveconfig.py -s -i CONFIG_SCSI -a all
  163. To control which ones are displayed, use -I <list> where list is a list of
  164. options (use '-I help' to see possible options and their meaning).
  165. To skip showing you options that already have an 'imply' attached, use -A.
  166. When you have finished adding 'imply' options you can regenerate the
  167. defconfig files for affected boards with something like:
  168. git show --stat | ./tools/moveconfig.py -s -d -
  169. This will regenerate only those defconfigs changed in the current commit.
  170. If you start with (say) 100 defconfigs being changed in the commit, and add
  171. a few 'imply' options as above, then regenerate, hopefully you can reduce the
  172. number of defconfigs changed in the commit.
  173. Available options
  174. -----------------
  175. -c, --color
  176. Surround each portion of the log with escape sequences to display it
  177. in color on the terminal.
  178. -C, --commit
  179. Create a git commit with the changes when the operation is complete. A
  180. standard commit message is used which may need to be edited.
  181. -d, --defconfigs
  182. Specify a file containing a list of defconfigs to move. The defconfig
  183. files can be given with shell-style wildcards. Use '-' to read from stdin.
  184. -n, --dry-run
  185. Perform a trial run that does not make any changes. It is useful to
  186. see what is going to happen before one actually runs it.
  187. -e, --exit-on-error
  188. Exit immediately if Make exits with a non-zero status while processing
  189. a defconfig file.
  190. -s, --force-sync
  191. Do "make savedefconfig" forcibly for all the defconfig files.
  192. If not specified, "make savedefconfig" only occurs for cases
  193. where at least one CONFIG was moved.
  194. -S, --spl
  195. Look for moved config options in spl/include/autoconf.mk instead of
  196. include/autoconf.mk. This is useful for moving options for SPL build
  197. because SPL related options (mostly prefixed with CONFIG_SPL_) are
  198. sometimes blocked by CONFIG_SPL_BUILD ifdef conditionals.
  199. -H, --headers-only
  200. Only cleanup the headers; skip the defconfig processing
  201. -j, --jobs
  202. Specify the number of threads to run simultaneously. If not specified,
  203. the number of threads is the same as the number of CPU cores.
  204. -r, --git-ref
  205. Specify the git ref to clone for building the autoconf.mk. If unspecified
  206. use the CWD. This is useful for when changes to the Kconfig affect the
  207. default values and you want to capture the state of the defconfig from
  208. before that change was in effect. If in doubt, specify a ref pre-Kconfig
  209. changes (use HEAD if Kconfig changes are not committed). Worst case it will
  210. take a bit longer to run, but will always do the right thing.
  211. -v, --verbose
  212. Show any build errors as boards are built
  213. -y, --yes
  214. Instead of prompting, automatically go ahead with all operations. This
  215. includes cleaning up headers, CONFIG_SYS_EXTRA_OPTIONS, the config whitelist
  216. and the README.
  217. To see the complete list of supported options, run
  218. $ tools/moveconfig.py -h
  219. """
  220. import collections
  221. import copy
  222. import difflib
  223. import filecmp
  224. import fnmatch
  225. import glob
  226. import multiprocessing
  227. import optparse
  228. import os
  229. import Queue
  230. import re
  231. import shutil
  232. import subprocess
  233. import sys
  234. import tempfile
  235. import threading
  236. import time
  237. sys.path.append(os.path.join(os.path.dirname(__file__), 'buildman'))
  238. sys.path.append(os.path.join(os.path.dirname(__file__), 'patman'))
  239. import bsettings
  240. import kconfiglib
  241. import toolchain
  242. SHOW_GNU_MAKE = 'scripts/show-gnu-make'
  243. SLEEP_TIME=0.03
  244. STATE_IDLE = 0
  245. STATE_DEFCONFIG = 1
  246. STATE_AUTOCONF = 2
  247. STATE_SAVEDEFCONFIG = 3
  248. ACTION_MOVE = 0
  249. ACTION_NO_ENTRY = 1
  250. ACTION_NO_ENTRY_WARN = 2
  251. ACTION_NO_CHANGE = 3
  252. COLOR_BLACK = '0;30'
  253. COLOR_RED = '0;31'
  254. COLOR_GREEN = '0;32'
  255. COLOR_BROWN = '0;33'
  256. COLOR_BLUE = '0;34'
  257. COLOR_PURPLE = '0;35'
  258. COLOR_CYAN = '0;36'
  259. COLOR_LIGHT_GRAY = '0;37'
  260. COLOR_DARK_GRAY = '1;30'
  261. COLOR_LIGHT_RED = '1;31'
  262. COLOR_LIGHT_GREEN = '1;32'
  263. COLOR_YELLOW = '1;33'
  264. COLOR_LIGHT_BLUE = '1;34'
  265. COLOR_LIGHT_PURPLE = '1;35'
  266. COLOR_LIGHT_CYAN = '1;36'
  267. COLOR_WHITE = '1;37'
  268. AUTO_CONF_PATH = 'include/config/auto.conf'
  269. CONFIG_DATABASE = 'moveconfig.db'
  270. CONFIG_LEN = len('CONFIG_')
  271. ### helper functions ###
  272. def get_devnull():
  273. """Get the file object of '/dev/null' device."""
  274. try:
  275. devnull = subprocess.DEVNULL # py3k
  276. except AttributeError:
  277. devnull = open(os.devnull, 'wb')
  278. return devnull
  279. def check_top_directory():
  280. """Exit if we are not at the top of source directory."""
  281. for f in ('README', 'Licenses'):
  282. if not os.path.exists(f):
  283. sys.exit('Please run at the top of source directory.')
  284. def check_clean_directory():
  285. """Exit if the source tree is not clean."""
  286. for f in ('.config', 'include/config'):
  287. if os.path.exists(f):
  288. sys.exit("source tree is not clean, please run 'make mrproper'")
  289. def get_make_cmd():
  290. """Get the command name of GNU Make.
  291. U-Boot needs GNU Make for building, but the command name is not
  292. necessarily "make". (for example, "gmake" on FreeBSD).
  293. Returns the most appropriate command name on your system.
  294. """
  295. process = subprocess.Popen([SHOW_GNU_MAKE], stdout=subprocess.PIPE)
  296. ret = process.communicate()
  297. if process.returncode:
  298. sys.exit('GNU Make not found')
  299. return ret[0].rstrip()
  300. def get_matched_defconfig(line):
  301. """Get the defconfig files that match a pattern
  302. Args:
  303. line: Path or filename to match, e.g. 'configs/snow_defconfig' or
  304. 'k2*_defconfig'. If no directory is provided, 'configs/' is
  305. prepended
  306. Returns:
  307. a list of matching defconfig files
  308. """
  309. dirname = os.path.dirname(line)
  310. if dirname:
  311. pattern = line
  312. else:
  313. pattern = os.path.join('configs', line)
  314. return glob.glob(pattern) + glob.glob(pattern + '_defconfig')
  315. def get_matched_defconfigs(defconfigs_file):
  316. """Get all the defconfig files that match the patterns in a file.
  317. Args:
  318. defconfigs_file: File containing a list of defconfigs to process, or
  319. '-' to read the list from stdin
  320. Returns:
  321. A list of paths to defconfig files, with no duplicates
  322. """
  323. defconfigs = []
  324. if defconfigs_file == '-':
  325. fd = sys.stdin
  326. defconfigs_file = 'stdin'
  327. else:
  328. fd = open(defconfigs_file)
  329. for i, line in enumerate(fd):
  330. line = line.strip()
  331. if not line:
  332. continue # skip blank lines silently
  333. if ' ' in line:
  334. line = line.split(' ')[0] # handle 'git log' input
  335. matched = get_matched_defconfig(line)
  336. if not matched:
  337. print >> sys.stderr, "warning: %s:%d: no defconfig matched '%s'" % \
  338. (defconfigs_file, i + 1, line)
  339. defconfigs += matched
  340. # use set() to drop multiple matching
  341. return [ defconfig[len('configs') + 1:] for defconfig in set(defconfigs) ]
  342. def get_all_defconfigs():
  343. """Get all the defconfig files under the configs/ directory."""
  344. defconfigs = []
  345. for (dirpath, dirnames, filenames) in os.walk('configs'):
  346. dirpath = dirpath[len('configs') + 1:]
  347. for filename in fnmatch.filter(filenames, '*_defconfig'):
  348. defconfigs.append(os.path.join(dirpath, filename))
  349. return defconfigs
  350. def color_text(color_enabled, color, string):
  351. """Return colored string."""
  352. if color_enabled:
  353. # LF should not be surrounded by the escape sequence.
  354. # Otherwise, additional whitespace or line-feed might be printed.
  355. return '\n'.join([ '\033[' + color + 'm' + s + '\033[0m' if s else ''
  356. for s in string.split('\n') ])
  357. else:
  358. return string
  359. def show_diff(a, b, file_path, color_enabled):
  360. """Show unidified diff.
  361. Arguments:
  362. a: A list of lines (before)
  363. b: A list of lines (after)
  364. file_path: Path to the file
  365. color_enabled: Display the diff in color
  366. """
  367. diff = difflib.unified_diff(a, b,
  368. fromfile=os.path.join('a', file_path),
  369. tofile=os.path.join('b', file_path))
  370. for line in diff:
  371. if line[0] == '-' and line[1] != '-':
  372. print color_text(color_enabled, COLOR_RED, line),
  373. elif line[0] == '+' and line[1] != '+':
  374. print color_text(color_enabled, COLOR_GREEN, line),
  375. else:
  376. print line,
  377. def extend_matched_lines(lines, matched, pre_patterns, post_patterns, extend_pre,
  378. extend_post):
  379. """Extend matched lines if desired patterns are found before/after already
  380. matched lines.
  381. Arguments:
  382. lines: A list of lines handled.
  383. matched: A list of line numbers that have been already matched.
  384. (will be updated by this function)
  385. pre_patterns: A list of regular expression that should be matched as
  386. preamble.
  387. post_patterns: A list of regular expression that should be matched as
  388. postamble.
  389. extend_pre: Add the line number of matched preamble to the matched list.
  390. extend_post: Add the line number of matched postamble to the matched list.
  391. """
  392. extended_matched = []
  393. j = matched[0]
  394. for i in matched:
  395. if i == 0 or i < j:
  396. continue
  397. j = i
  398. while j in matched:
  399. j += 1
  400. if j >= len(lines):
  401. break
  402. for p in pre_patterns:
  403. if p.search(lines[i - 1]):
  404. break
  405. else:
  406. # not matched
  407. continue
  408. for p in post_patterns:
  409. if p.search(lines[j]):
  410. break
  411. else:
  412. # not matched
  413. continue
  414. if extend_pre:
  415. extended_matched.append(i - 1)
  416. if extend_post:
  417. extended_matched.append(j)
  418. matched += extended_matched
  419. matched.sort()
  420. def confirm(options, prompt):
  421. if not options.yes:
  422. while True:
  423. choice = raw_input('{} [y/n]: '.format(prompt))
  424. choice = choice.lower()
  425. print choice
  426. if choice == 'y' or choice == 'n':
  427. break
  428. if choice == 'n':
  429. return False
  430. return True
  431. def cleanup_one_header(header_path, patterns, options):
  432. """Clean regex-matched lines away from a file.
  433. Arguments:
  434. header_path: path to the cleaned file.
  435. patterns: list of regex patterns. Any lines matching to these
  436. patterns are deleted.
  437. options: option flags.
  438. """
  439. with open(header_path) as f:
  440. lines = f.readlines()
  441. matched = []
  442. for i, line in enumerate(lines):
  443. if i - 1 in matched and lines[i - 1][-2:] == '\\\n':
  444. matched.append(i)
  445. continue
  446. for pattern in patterns:
  447. if pattern.search(line):
  448. matched.append(i)
  449. break
  450. if not matched:
  451. return
  452. # remove empty #ifdef ... #endif, successive blank lines
  453. pattern_if = re.compile(r'#\s*if(def|ndef)?\W') # #if, #ifdef, #ifndef
  454. pattern_elif = re.compile(r'#\s*el(if|se)\W') # #elif, #else
  455. pattern_endif = re.compile(r'#\s*endif\W') # #endif
  456. pattern_blank = re.compile(r'^\s*$') # empty line
  457. while True:
  458. old_matched = copy.copy(matched)
  459. extend_matched_lines(lines, matched, [pattern_if],
  460. [pattern_endif], True, True)
  461. extend_matched_lines(lines, matched, [pattern_elif],
  462. [pattern_elif, pattern_endif], True, False)
  463. extend_matched_lines(lines, matched, [pattern_if, pattern_elif],
  464. [pattern_blank], False, True)
  465. extend_matched_lines(lines, matched, [pattern_blank],
  466. [pattern_elif, pattern_endif], True, False)
  467. extend_matched_lines(lines, matched, [pattern_blank],
  468. [pattern_blank], True, False)
  469. if matched == old_matched:
  470. break
  471. tolines = copy.copy(lines)
  472. for i in reversed(matched):
  473. tolines.pop(i)
  474. show_diff(lines, tolines, header_path, options.color)
  475. if options.dry_run:
  476. return
  477. with open(header_path, 'w') as f:
  478. for line in tolines:
  479. f.write(line)
  480. def cleanup_headers(configs, options):
  481. """Delete config defines from board headers.
  482. Arguments:
  483. configs: A list of CONFIGs to remove.
  484. options: option flags.
  485. """
  486. if not confirm(options, 'Clean up headers?'):
  487. return
  488. patterns = []
  489. for config in configs:
  490. patterns.append(re.compile(r'#\s*define\s+%s\W' % config))
  491. patterns.append(re.compile(r'#\s*undef\s+%s\W' % config))
  492. for dir in 'include', 'arch', 'board':
  493. for (dirpath, dirnames, filenames) in os.walk(dir):
  494. if dirpath == os.path.join('include', 'generated'):
  495. continue
  496. for filename in filenames:
  497. if not fnmatch.fnmatch(filename, '*~'):
  498. cleanup_one_header(os.path.join(dirpath, filename),
  499. patterns, options)
  500. def cleanup_one_extra_option(defconfig_path, configs, options):
  501. """Delete config defines in CONFIG_SYS_EXTRA_OPTIONS in one defconfig file.
  502. Arguments:
  503. defconfig_path: path to the cleaned defconfig file.
  504. configs: A list of CONFIGs to remove.
  505. options: option flags.
  506. """
  507. start = 'CONFIG_SYS_EXTRA_OPTIONS="'
  508. end = '"\n'
  509. with open(defconfig_path) as f:
  510. lines = f.readlines()
  511. for i, line in enumerate(lines):
  512. if line.startswith(start) and line.endswith(end):
  513. break
  514. else:
  515. # CONFIG_SYS_EXTRA_OPTIONS was not found in this defconfig
  516. return
  517. old_tokens = line[len(start):-len(end)].split(',')
  518. new_tokens = []
  519. for token in old_tokens:
  520. pos = token.find('=')
  521. if not (token[:pos] if pos >= 0 else token) in configs:
  522. new_tokens.append(token)
  523. if new_tokens == old_tokens:
  524. return
  525. tolines = copy.copy(lines)
  526. if new_tokens:
  527. tolines[i] = start + ','.join(new_tokens) + end
  528. else:
  529. tolines.pop(i)
  530. show_diff(lines, tolines, defconfig_path, options.color)
  531. if options.dry_run:
  532. return
  533. with open(defconfig_path, 'w') as f:
  534. for line in tolines:
  535. f.write(line)
  536. def cleanup_extra_options(configs, options):
  537. """Delete config defines in CONFIG_SYS_EXTRA_OPTIONS in defconfig files.
  538. Arguments:
  539. configs: A list of CONFIGs to remove.
  540. options: option flags.
  541. """
  542. if not confirm(options, 'Clean up CONFIG_SYS_EXTRA_OPTIONS?'):
  543. return
  544. configs = [ config[len('CONFIG_'):] for config in configs ]
  545. defconfigs = get_all_defconfigs()
  546. for defconfig in defconfigs:
  547. cleanup_one_extra_option(os.path.join('configs', defconfig), configs,
  548. options)
  549. def cleanup_whitelist(configs, options):
  550. """Delete config whitelist entries
  551. Arguments:
  552. configs: A list of CONFIGs to remove.
  553. options: option flags.
  554. """
  555. if not confirm(options, 'Clean up whitelist entries?'):
  556. return
  557. with open(os.path.join('scripts', 'config_whitelist.txt')) as f:
  558. lines = f.readlines()
  559. lines = [x for x in lines if x.strip() not in configs]
  560. with open(os.path.join('scripts', 'config_whitelist.txt'), 'w') as f:
  561. f.write(''.join(lines))
  562. def find_matching(patterns, line):
  563. for pat in patterns:
  564. if pat.search(line):
  565. return True
  566. return False
  567. def cleanup_readme(configs, options):
  568. """Delete config description in README
  569. Arguments:
  570. configs: A list of CONFIGs to remove.
  571. options: option flags.
  572. """
  573. if not confirm(options, 'Clean up README?'):
  574. return
  575. patterns = []
  576. for config in configs:
  577. patterns.append(re.compile(r'^\s+%s' % config))
  578. with open('README') as f:
  579. lines = f.readlines()
  580. found = False
  581. newlines = []
  582. for line in lines:
  583. if not found:
  584. found = find_matching(patterns, line)
  585. if found:
  586. continue
  587. if found and re.search(r'^\s+CONFIG', line):
  588. found = False
  589. if not found:
  590. newlines.append(line)
  591. with open('README', 'w') as f:
  592. f.write(''.join(newlines))
  593. ### classes ###
  594. class Progress:
  595. """Progress Indicator"""
  596. def __init__(self, total):
  597. """Create a new progress indicator.
  598. Arguments:
  599. total: A number of defconfig files to process.
  600. """
  601. self.current = 0
  602. self.total = total
  603. def inc(self):
  604. """Increment the number of processed defconfig files."""
  605. self.current += 1
  606. def show(self):
  607. """Display the progress."""
  608. print ' %d defconfigs out of %d\r' % (self.current, self.total),
  609. sys.stdout.flush()
  610. class KconfigScanner:
  611. """Kconfig scanner."""
  612. def __init__(self):
  613. """Scan all the Kconfig files and create a Config object."""
  614. # Define environment variables referenced from Kconfig
  615. os.environ['srctree'] = os.getcwd()
  616. os.environ['UBOOTVERSION'] = 'dummy'
  617. os.environ['KCONFIG_OBJDIR'] = ''
  618. self.conf = kconfiglib.Config()
  619. class KconfigParser:
  620. """A parser of .config and include/autoconf.mk."""
  621. re_arch = re.compile(r'CONFIG_SYS_ARCH="(.*)"')
  622. re_cpu = re.compile(r'CONFIG_SYS_CPU="(.*)"')
  623. def __init__(self, configs, options, build_dir):
  624. """Create a new parser.
  625. Arguments:
  626. configs: A list of CONFIGs to move.
  627. options: option flags.
  628. build_dir: Build directory.
  629. """
  630. self.configs = configs
  631. self.options = options
  632. self.dotconfig = os.path.join(build_dir, '.config')
  633. self.autoconf = os.path.join(build_dir, 'include', 'autoconf.mk')
  634. self.spl_autoconf = os.path.join(build_dir, 'spl', 'include',
  635. 'autoconf.mk')
  636. self.config_autoconf = os.path.join(build_dir, AUTO_CONF_PATH)
  637. self.defconfig = os.path.join(build_dir, 'defconfig')
  638. def get_arch(self):
  639. """Parse .config file and return the architecture.
  640. Returns:
  641. Architecture name (e.g. 'arm').
  642. """
  643. arch = ''
  644. cpu = ''
  645. for line in open(self.dotconfig):
  646. m = self.re_arch.match(line)
  647. if m:
  648. arch = m.group(1)
  649. continue
  650. m = self.re_cpu.match(line)
  651. if m:
  652. cpu = m.group(1)
  653. if not arch:
  654. return None
  655. # fix-up for aarch64
  656. if arch == 'arm' and cpu == 'armv8':
  657. arch = 'aarch64'
  658. return arch
  659. def parse_one_config(self, config, dotconfig_lines, autoconf_lines):
  660. """Parse .config, defconfig, include/autoconf.mk for one config.
  661. This function looks for the config options in the lines from
  662. defconfig, .config, and include/autoconf.mk in order to decide
  663. which action should be taken for this defconfig.
  664. Arguments:
  665. config: CONFIG name to parse.
  666. dotconfig_lines: lines from the .config file.
  667. autoconf_lines: lines from the include/autoconf.mk file.
  668. Returns:
  669. A tupple of the action for this defconfig and the line
  670. matched for the config.
  671. """
  672. not_set = '# %s is not set' % config
  673. for line in autoconf_lines:
  674. line = line.rstrip()
  675. if line.startswith(config + '='):
  676. new_val = line
  677. break
  678. else:
  679. new_val = not_set
  680. for line in dotconfig_lines:
  681. line = line.rstrip()
  682. if line.startswith(config + '=') or line == not_set:
  683. old_val = line
  684. break
  685. else:
  686. if new_val == not_set:
  687. return (ACTION_NO_ENTRY, config)
  688. else:
  689. return (ACTION_NO_ENTRY_WARN, config)
  690. # If this CONFIG is neither bool nor trisate
  691. if old_val[-2:] != '=y' and old_val[-2:] != '=m' and old_val != not_set:
  692. # tools/scripts/define2mk.sed changes '1' to 'y'.
  693. # This is a problem if the CONFIG is int type.
  694. # Check the type in Kconfig and handle it correctly.
  695. if new_val[-2:] == '=y':
  696. new_val = new_val[:-1] + '1'
  697. return (ACTION_NO_CHANGE if old_val == new_val else ACTION_MOVE,
  698. new_val)
  699. def update_dotconfig(self):
  700. """Parse files for the config options and update the .config.
  701. This function parses the generated .config and include/autoconf.mk
  702. searching the target options.
  703. Move the config option(s) to the .config as needed.
  704. Arguments:
  705. defconfig: defconfig name.
  706. Returns:
  707. Return a tuple of (updated flag, log string).
  708. The "updated flag" is True if the .config was updated, False
  709. otherwise. The "log string" shows what happend to the .config.
  710. """
  711. results = []
  712. updated = False
  713. suspicious = False
  714. rm_files = [self.config_autoconf, self.autoconf]
  715. if self.options.spl:
  716. if os.path.exists(self.spl_autoconf):
  717. autoconf_path = self.spl_autoconf
  718. rm_files.append(self.spl_autoconf)
  719. else:
  720. for f in rm_files:
  721. os.remove(f)
  722. return (updated, suspicious,
  723. color_text(self.options.color, COLOR_BROWN,
  724. "SPL is not enabled. Skipped.") + '\n')
  725. else:
  726. autoconf_path = self.autoconf
  727. with open(self.dotconfig) as f:
  728. dotconfig_lines = f.readlines()
  729. with open(autoconf_path) as f:
  730. autoconf_lines = f.readlines()
  731. for config in self.configs:
  732. result = self.parse_one_config(config, dotconfig_lines,
  733. autoconf_lines)
  734. results.append(result)
  735. log = ''
  736. for (action, value) in results:
  737. if action == ACTION_MOVE:
  738. actlog = "Move '%s'" % value
  739. log_color = COLOR_LIGHT_GREEN
  740. elif action == ACTION_NO_ENTRY:
  741. actlog = "%s is not defined in Kconfig. Do nothing." % value
  742. log_color = COLOR_LIGHT_BLUE
  743. elif action == ACTION_NO_ENTRY_WARN:
  744. actlog = "%s is not defined in Kconfig (suspicious). Do nothing." % value
  745. log_color = COLOR_YELLOW
  746. suspicious = True
  747. elif action == ACTION_NO_CHANGE:
  748. actlog = "'%s' is the same as the define in Kconfig. Do nothing." \
  749. % value
  750. log_color = COLOR_LIGHT_PURPLE
  751. elif action == ACTION_SPL_NOT_EXIST:
  752. actlog = "SPL is not enabled for this defconfig. Skip."
  753. log_color = COLOR_PURPLE
  754. else:
  755. sys.exit("Internal Error. This should not happen.")
  756. log += color_text(self.options.color, log_color, actlog) + '\n'
  757. with open(self.dotconfig, 'a') as f:
  758. for (action, value) in results:
  759. if action == ACTION_MOVE:
  760. f.write(value + '\n')
  761. updated = True
  762. self.results = results
  763. for f in rm_files:
  764. os.remove(f)
  765. return (updated, suspicious, log)
  766. def check_defconfig(self):
  767. """Check the defconfig after savedefconfig
  768. Returns:
  769. Return additional log if moved CONFIGs were removed again by
  770. 'make savedefconfig'.
  771. """
  772. log = ''
  773. with open(self.defconfig) as f:
  774. defconfig_lines = f.readlines()
  775. for (action, value) in self.results:
  776. if action != ACTION_MOVE:
  777. continue
  778. if not value + '\n' in defconfig_lines:
  779. log += color_text(self.options.color, COLOR_YELLOW,
  780. "'%s' was removed by savedefconfig.\n" %
  781. value)
  782. return log
  783. class DatabaseThread(threading.Thread):
  784. """This thread processes results from Slot threads.
  785. It collects the data in the master config directary. There is only one
  786. result thread, and this helps to serialise the build output.
  787. """
  788. def __init__(self, config_db, db_queue):
  789. """Set up a new result thread
  790. Args:
  791. builder: Builder which will be sent each result
  792. """
  793. threading.Thread.__init__(self)
  794. self.config_db = config_db
  795. self.db_queue= db_queue
  796. def run(self):
  797. """Called to start up the result thread.
  798. We collect the next result job and pass it on to the build.
  799. """
  800. while True:
  801. defconfig, configs = self.db_queue.get()
  802. self.config_db[defconfig] = configs
  803. self.db_queue.task_done()
  804. class Slot:
  805. """A slot to store a subprocess.
  806. Each instance of this class handles one subprocess.
  807. This class is useful to control multiple threads
  808. for faster processing.
  809. """
  810. def __init__(self, toolchains, configs, options, progress, devnull,
  811. make_cmd, reference_src_dir, db_queue):
  812. """Create a new process slot.
  813. Arguments:
  814. toolchains: Toolchains object containing toolchains.
  815. configs: A list of CONFIGs to move.
  816. options: option flags.
  817. progress: A progress indicator.
  818. devnull: A file object of '/dev/null'.
  819. make_cmd: command name of GNU Make.
  820. reference_src_dir: Determine the true starting config state from this
  821. source tree.
  822. db_queue: output queue to write config info for the database
  823. """
  824. self.toolchains = toolchains
  825. self.options = options
  826. self.progress = progress
  827. self.build_dir = tempfile.mkdtemp()
  828. self.devnull = devnull
  829. self.make_cmd = (make_cmd, 'O=' + self.build_dir)
  830. self.reference_src_dir = reference_src_dir
  831. self.db_queue = db_queue
  832. self.parser = KconfigParser(configs, options, self.build_dir)
  833. self.state = STATE_IDLE
  834. self.failed_boards = set()
  835. self.suspicious_boards = set()
  836. def __del__(self):
  837. """Delete the working directory
  838. This function makes sure the temporary directory is cleaned away
  839. even if Python suddenly dies due to error. It should be done in here
  840. because it is guaranteed the destructor is always invoked when the
  841. instance of the class gets unreferenced.
  842. If the subprocess is still running, wait until it finishes.
  843. """
  844. if self.state != STATE_IDLE:
  845. while self.ps.poll() == None:
  846. pass
  847. shutil.rmtree(self.build_dir)
  848. def add(self, defconfig):
  849. """Assign a new subprocess for defconfig and add it to the slot.
  850. If the slot is vacant, create a new subprocess for processing the
  851. given defconfig and add it to the slot. Just returns False if
  852. the slot is occupied (i.e. the current subprocess is still running).
  853. Arguments:
  854. defconfig: defconfig name.
  855. Returns:
  856. Return True on success or False on failure
  857. """
  858. if self.state != STATE_IDLE:
  859. return False
  860. self.defconfig = defconfig
  861. self.log = ''
  862. self.current_src_dir = self.reference_src_dir
  863. self.do_defconfig()
  864. return True
  865. def poll(self):
  866. """Check the status of the subprocess and handle it as needed.
  867. Returns True if the slot is vacant (i.e. in idle state).
  868. If the configuration is successfully finished, assign a new
  869. subprocess to build include/autoconf.mk.
  870. If include/autoconf.mk is generated, invoke the parser to
  871. parse the .config and the include/autoconf.mk, moving
  872. config options to the .config as needed.
  873. If the .config was updated, run "make savedefconfig" to sync
  874. it, update the original defconfig, and then set the slot back
  875. to the idle state.
  876. Returns:
  877. Return True if the subprocess is terminated, False otherwise
  878. """
  879. if self.state == STATE_IDLE:
  880. return True
  881. if self.ps.poll() == None:
  882. return False
  883. if self.ps.poll() != 0:
  884. self.handle_error()
  885. elif self.state == STATE_DEFCONFIG:
  886. if self.reference_src_dir and not self.current_src_dir:
  887. self.do_savedefconfig()
  888. else:
  889. self.do_autoconf()
  890. elif self.state == STATE_AUTOCONF:
  891. if self.current_src_dir:
  892. self.current_src_dir = None
  893. self.do_defconfig()
  894. elif self.options.build_db:
  895. self.do_build_db()
  896. else:
  897. self.do_savedefconfig()
  898. elif self.state == STATE_SAVEDEFCONFIG:
  899. self.update_defconfig()
  900. else:
  901. sys.exit("Internal Error. This should not happen.")
  902. return True if self.state == STATE_IDLE else False
  903. def handle_error(self):
  904. """Handle error cases."""
  905. self.log += color_text(self.options.color, COLOR_LIGHT_RED,
  906. "Failed to process.\n")
  907. if self.options.verbose:
  908. self.log += color_text(self.options.color, COLOR_LIGHT_CYAN,
  909. self.ps.stderr.read())
  910. self.finish(False)
  911. def do_defconfig(self):
  912. """Run 'make <board>_defconfig' to create the .config file."""
  913. cmd = list(self.make_cmd)
  914. cmd.append(self.defconfig)
  915. self.ps = subprocess.Popen(cmd, stdout=self.devnull,
  916. stderr=subprocess.PIPE,
  917. cwd=self.current_src_dir)
  918. self.state = STATE_DEFCONFIG
  919. def do_autoconf(self):
  920. """Run 'make AUTO_CONF_PATH'."""
  921. arch = self.parser.get_arch()
  922. try:
  923. toolchain = self.toolchains.Select(arch)
  924. except ValueError:
  925. self.log += color_text(self.options.color, COLOR_YELLOW,
  926. "Tool chain for '%s' is missing. Do nothing.\n % arch")
  927. self.finish(False)
  928. return
  929. env = toolchain.MakeEnvironment(False)
  930. cmd = list(self.make_cmd)
  931. cmd.append('KCONFIG_IGNORE_DUPLICATES=1')
  932. cmd.append(AUTO_CONF_PATH)
  933. self.ps = subprocess.Popen(cmd, stdout=self.devnull, env=env,
  934. stderr=subprocess.PIPE,
  935. cwd=self.current_src_dir)
  936. self.state = STATE_AUTOCONF
  937. def do_build_db(self):
  938. """Add the board to the database"""
  939. configs = {}
  940. with open(os.path.join(self.build_dir, AUTO_CONF_PATH)) as fd:
  941. for line in fd.readlines():
  942. if line.startswith('CONFIG'):
  943. config, value = line.split('=', 1)
  944. configs[config] = value.rstrip()
  945. self.db_queue.put([self.defconfig, configs])
  946. self.finish(True)
  947. def do_savedefconfig(self):
  948. """Update the .config and run 'make savedefconfig'."""
  949. (updated, suspicious, log) = self.parser.update_dotconfig()
  950. if suspicious:
  951. self.suspicious_boards.add(self.defconfig)
  952. self.log += log
  953. if not self.options.force_sync and not updated:
  954. self.finish(True)
  955. return
  956. if updated:
  957. self.log += color_text(self.options.color, COLOR_LIGHT_GREEN,
  958. "Syncing by savedefconfig...\n")
  959. else:
  960. self.log += "Syncing by savedefconfig (forced by option)...\n"
  961. cmd = list(self.make_cmd)
  962. cmd.append('savedefconfig')
  963. self.ps = subprocess.Popen(cmd, stdout=self.devnull,
  964. stderr=subprocess.PIPE)
  965. self.state = STATE_SAVEDEFCONFIG
  966. def update_defconfig(self):
  967. """Update the input defconfig and go back to the idle state."""
  968. log = self.parser.check_defconfig()
  969. if log:
  970. self.suspicious_boards.add(self.defconfig)
  971. self.log += log
  972. orig_defconfig = os.path.join('configs', self.defconfig)
  973. new_defconfig = os.path.join(self.build_dir, 'defconfig')
  974. updated = not filecmp.cmp(orig_defconfig, new_defconfig)
  975. if updated:
  976. self.log += color_text(self.options.color, COLOR_LIGHT_BLUE,
  977. "defconfig was updated.\n")
  978. if not self.options.dry_run and updated:
  979. shutil.move(new_defconfig, orig_defconfig)
  980. self.finish(True)
  981. def finish(self, success):
  982. """Display log along with progress and go to the idle state.
  983. Arguments:
  984. success: Should be True when the defconfig was processed
  985. successfully, or False when it fails.
  986. """
  987. # output at least 30 characters to hide the "* defconfigs out of *".
  988. log = self.defconfig.ljust(30) + '\n'
  989. log += '\n'.join([ ' ' + s for s in self.log.split('\n') ])
  990. # Some threads are running in parallel.
  991. # Print log atomically to not mix up logs from different threads.
  992. print >> (sys.stdout if success else sys.stderr), log
  993. if not success:
  994. if self.options.exit_on_error:
  995. sys.exit("Exit on error.")
  996. # If --exit-on-error flag is not set, skip this board and continue.
  997. # Record the failed board.
  998. self.failed_boards.add(self.defconfig)
  999. self.progress.inc()
  1000. self.progress.show()
  1001. self.state = STATE_IDLE
  1002. def get_failed_boards(self):
  1003. """Returns a set of failed boards (defconfigs) in this slot.
  1004. """
  1005. return self.failed_boards
  1006. def get_suspicious_boards(self):
  1007. """Returns a set of boards (defconfigs) with possible misconversion.
  1008. """
  1009. return self.suspicious_boards - self.failed_boards
  1010. class Slots:
  1011. """Controller of the array of subprocess slots."""
  1012. def __init__(self, toolchains, configs, options, progress,
  1013. reference_src_dir, db_queue):
  1014. """Create a new slots controller.
  1015. Arguments:
  1016. toolchains: Toolchains object containing toolchains.
  1017. configs: A list of CONFIGs to move.
  1018. options: option flags.
  1019. progress: A progress indicator.
  1020. reference_src_dir: Determine the true starting config state from this
  1021. source tree.
  1022. db_queue: output queue to write config info for the database
  1023. """
  1024. self.options = options
  1025. self.slots = []
  1026. devnull = get_devnull()
  1027. make_cmd = get_make_cmd()
  1028. for i in range(options.jobs):
  1029. self.slots.append(Slot(toolchains, configs, options, progress,
  1030. devnull, make_cmd, reference_src_dir,
  1031. db_queue))
  1032. def add(self, defconfig):
  1033. """Add a new subprocess if a vacant slot is found.
  1034. Arguments:
  1035. defconfig: defconfig name to be put into.
  1036. Returns:
  1037. Return True on success or False on failure
  1038. """
  1039. for slot in self.slots:
  1040. if slot.add(defconfig):
  1041. return True
  1042. return False
  1043. def available(self):
  1044. """Check if there is a vacant slot.
  1045. Returns:
  1046. Return True if at lease one vacant slot is found, False otherwise.
  1047. """
  1048. for slot in self.slots:
  1049. if slot.poll():
  1050. return True
  1051. return False
  1052. def empty(self):
  1053. """Check if all slots are vacant.
  1054. Returns:
  1055. Return True if all the slots are vacant, False otherwise.
  1056. """
  1057. ret = True
  1058. for slot in self.slots:
  1059. if not slot.poll():
  1060. ret = False
  1061. return ret
  1062. def show_failed_boards(self):
  1063. """Display all of the failed boards (defconfigs)."""
  1064. boards = set()
  1065. output_file = 'moveconfig.failed'
  1066. for slot in self.slots:
  1067. boards |= slot.get_failed_boards()
  1068. if boards:
  1069. boards = '\n'.join(boards) + '\n'
  1070. msg = "The following boards were not processed due to error:\n"
  1071. msg += boards
  1072. msg += "(the list has been saved in %s)\n" % output_file
  1073. print >> sys.stderr, color_text(self.options.color, COLOR_LIGHT_RED,
  1074. msg)
  1075. with open(output_file, 'w') as f:
  1076. f.write(boards)
  1077. def show_suspicious_boards(self):
  1078. """Display all boards (defconfigs) with possible misconversion."""
  1079. boards = set()
  1080. output_file = 'moveconfig.suspicious'
  1081. for slot in self.slots:
  1082. boards |= slot.get_suspicious_boards()
  1083. if boards:
  1084. boards = '\n'.join(boards) + '\n'
  1085. msg = "The following boards might have been converted incorrectly.\n"
  1086. msg += "It is highly recommended to check them manually:\n"
  1087. msg += boards
  1088. msg += "(the list has been saved in %s)\n" % output_file
  1089. print >> sys.stderr, color_text(self.options.color, COLOR_YELLOW,
  1090. msg)
  1091. with open(output_file, 'w') as f:
  1092. f.write(boards)
  1093. class ReferenceSource:
  1094. """Reference source against which original configs should be parsed."""
  1095. def __init__(self, commit):
  1096. """Create a reference source directory based on a specified commit.
  1097. Arguments:
  1098. commit: commit to git-clone
  1099. """
  1100. self.src_dir = tempfile.mkdtemp()
  1101. print "Cloning git repo to a separate work directory..."
  1102. subprocess.check_output(['git', 'clone', os.getcwd(), '.'],
  1103. cwd=self.src_dir)
  1104. print "Checkout '%s' to build the original autoconf.mk." % \
  1105. subprocess.check_output(['git', 'rev-parse', '--short', commit]).strip()
  1106. subprocess.check_output(['git', 'checkout', commit],
  1107. stderr=subprocess.STDOUT, cwd=self.src_dir)
  1108. def __del__(self):
  1109. """Delete the reference source directory
  1110. This function makes sure the temporary directory is cleaned away
  1111. even if Python suddenly dies due to error. It should be done in here
  1112. because it is guaranteed the destructor is always invoked when the
  1113. instance of the class gets unreferenced.
  1114. """
  1115. shutil.rmtree(self.src_dir)
  1116. def get_dir(self):
  1117. """Return the absolute path to the reference source directory."""
  1118. return self.src_dir
  1119. def move_config(toolchains, configs, options, db_queue):
  1120. """Move config options to defconfig files.
  1121. Arguments:
  1122. configs: A list of CONFIGs to move.
  1123. options: option flags
  1124. """
  1125. if len(configs) == 0:
  1126. if options.force_sync:
  1127. print 'No CONFIG is specified. You are probably syncing defconfigs.',
  1128. elif options.build_db:
  1129. print 'Building %s database' % CONFIG_DATABASE
  1130. else:
  1131. print 'Neither CONFIG nor --force-sync is specified. Nothing will happen.',
  1132. else:
  1133. print 'Move ' + ', '.join(configs),
  1134. print '(jobs: %d)\n' % options.jobs
  1135. if options.git_ref:
  1136. reference_src = ReferenceSource(options.git_ref)
  1137. reference_src_dir = reference_src.get_dir()
  1138. else:
  1139. reference_src_dir = None
  1140. if options.defconfigs:
  1141. defconfigs = get_matched_defconfigs(options.defconfigs)
  1142. else:
  1143. defconfigs = get_all_defconfigs()
  1144. progress = Progress(len(defconfigs))
  1145. slots = Slots(toolchains, configs, options, progress, reference_src_dir,
  1146. db_queue)
  1147. # Main loop to process defconfig files:
  1148. # Add a new subprocess into a vacant slot.
  1149. # Sleep if there is no available slot.
  1150. for defconfig in defconfigs:
  1151. while not slots.add(defconfig):
  1152. while not slots.available():
  1153. # No available slot: sleep for a while
  1154. time.sleep(SLEEP_TIME)
  1155. # wait until all the subprocesses finish
  1156. while not slots.empty():
  1157. time.sleep(SLEEP_TIME)
  1158. print ''
  1159. slots.show_failed_boards()
  1160. slots.show_suspicious_boards()
  1161. def find_kconfig_rules(kconf, config, imply_config):
  1162. """Check whether a config has a 'select' or 'imply' keyword
  1163. Args:
  1164. kconf: Kconfig.Config object
  1165. config: Name of config to check (without CONFIG_ prefix)
  1166. imply_config: Implying config (without CONFIG_ prefix) which may or
  1167. may not have an 'imply' for 'config')
  1168. Returns:
  1169. Symbol object for 'config' if found, else None
  1170. """
  1171. sym = kconf.get_symbol(imply_config)
  1172. if sym:
  1173. for sel in sym.get_selected_symbols():
  1174. if sel.get_name() == config:
  1175. return sym
  1176. return None
  1177. def check_imply_rule(kconf, config, imply_config):
  1178. """Check if we can add an 'imply' option
  1179. This finds imply_config in the Kconfig and looks to see if it is possible
  1180. to add an 'imply' for 'config' to that part of the Kconfig.
  1181. Args:
  1182. kconf: Kconfig.Config object
  1183. config: Name of config to check (without CONFIG_ prefix)
  1184. imply_config: Implying config (without CONFIG_ prefix) which may or
  1185. may not have an 'imply' for 'config')
  1186. Returns:
  1187. tuple:
  1188. filename of Kconfig file containing imply_config, or None if none
  1189. line number within the Kconfig file, or 0 if none
  1190. message indicating the result
  1191. """
  1192. sym = kconf.get_symbol(imply_config)
  1193. if not sym:
  1194. return 'cannot find sym'
  1195. locs = sym.get_def_locations()
  1196. if len(locs) != 1:
  1197. return '%d locations' % len(locs)
  1198. fname, linenum = locs[0]
  1199. cwd = os.getcwd()
  1200. if cwd and fname.startswith(cwd):
  1201. fname = fname[len(cwd) + 1:]
  1202. file_line = ' at %s:%d' % (fname, linenum)
  1203. with open(fname) as fd:
  1204. data = fd.read().splitlines()
  1205. if data[linenum - 1] != 'config %s' % imply_config:
  1206. return None, 0, 'bad sym format %s%s' % (data[linenum], file_line)
  1207. return fname, linenum, 'adding%s' % file_line
  1208. def add_imply_rule(config, fname, linenum):
  1209. """Add a new 'imply' option to a Kconfig
  1210. Args:
  1211. config: config option to add an imply for (without CONFIG_ prefix)
  1212. fname: Kconfig filename to update
  1213. linenum: Line number to place the 'imply' before
  1214. Returns:
  1215. Message indicating the result
  1216. """
  1217. file_line = ' at %s:%d' % (fname, linenum)
  1218. data = open(fname).read().splitlines()
  1219. linenum -= 1
  1220. for offset, line in enumerate(data[linenum:]):
  1221. if line.strip().startswith('help') or not line:
  1222. data.insert(linenum + offset, '\timply %s' % config)
  1223. with open(fname, 'w') as fd:
  1224. fd.write('\n'.join(data) + '\n')
  1225. return 'added%s' % file_line
  1226. return 'could not insert%s'
  1227. (IMPLY_MIN_2, IMPLY_TARGET, IMPLY_CMD, IMPLY_NON_ARCH_BOARD) = (
  1228. 1, 2, 4, 8)
  1229. IMPLY_FLAGS = {
  1230. 'min2': [IMPLY_MIN_2, 'Show options which imply >2 boards (normally >5)'],
  1231. 'target': [IMPLY_TARGET, 'Allow CONFIG_TARGET_... options to imply'],
  1232. 'cmd': [IMPLY_CMD, 'Allow CONFIG_CMD_... to imply'],
  1233. 'non-arch-board': [
  1234. IMPLY_NON_ARCH_BOARD,
  1235. 'Allow Kconfig options outside arch/ and /board/ to imply'],
  1236. };
  1237. def do_imply_config(config_list, add_imply, imply_flags, skip_added,
  1238. check_kconfig=True, find_superset=False):
  1239. """Find CONFIG options which imply those in the list
  1240. Some CONFIG options can be implied by others and this can help to reduce
  1241. the size of the defconfig files. For example, CONFIG_X86 implies
  1242. CONFIG_CMD_IRQ, so we can put 'imply CMD_IRQ' under 'config X86' and
  1243. all x86 boards will have that option, avoiding adding CONFIG_CMD_IRQ to
  1244. each of the x86 defconfig files.
  1245. This function uses the moveconfig database to find such options. It
  1246. displays a list of things that could possibly imply those in the list.
  1247. The algorithm ignores any that start with CONFIG_TARGET since these
  1248. typically refer to only a few defconfigs (often one). It also does not
  1249. display a config with less than 5 defconfigs.
  1250. The algorithm works using sets. For each target config in config_list:
  1251. - Get the set 'defconfigs' which use that target config
  1252. - For each config (from a list of all configs):
  1253. - Get the set 'imply_defconfig' of defconfigs which use that config
  1254. -
  1255. - If imply_defconfigs contains anything not in defconfigs then
  1256. this config does not imply the target config
  1257. Params:
  1258. config_list: List of CONFIG options to check (each a string)
  1259. add_imply: Automatically add an 'imply' for each config.
  1260. imply_flags: Flags which control which implying configs are allowed
  1261. (IMPLY_...)
  1262. skip_added: Don't show options which already have an imply added.
  1263. check_kconfig: Check if implied symbols already have an 'imply' or
  1264. 'select' for the target config, and show this information if so.
  1265. find_superset: True to look for configs which are a superset of those
  1266. already found. So for example if CONFIG_EXYNOS5 implies an option,
  1267. but CONFIG_EXYNOS covers a larger set of defconfigs and also
  1268. implies that option, this will drop the former in favour of the
  1269. latter. In practice this option has not proved very used.
  1270. Note the terminoloy:
  1271. config - a CONFIG_XXX options (a string, e.g. 'CONFIG_CMD_EEPROM')
  1272. defconfig - a defconfig file (a string, e.g. 'configs/snow_defconfig')
  1273. """
  1274. kconf = KconfigScanner().conf if check_kconfig else None
  1275. if add_imply and add_imply != 'all':
  1276. add_imply = add_imply.split()
  1277. # key is defconfig name, value is dict of (CONFIG_xxx, value)
  1278. config_db = {}
  1279. # Holds a dict containing the set of defconfigs that contain each config
  1280. # key is config, value is set of defconfigs using that config
  1281. defconfig_db = collections.defaultdict(set)
  1282. # Set of all config options we have seen
  1283. all_configs = set()
  1284. # Set of all defconfigs we have seen
  1285. all_defconfigs = set()
  1286. # Read in the database
  1287. configs = {}
  1288. with open(CONFIG_DATABASE) as fd:
  1289. for line in fd.readlines():
  1290. line = line.rstrip()
  1291. if not line: # Separator between defconfigs
  1292. config_db[defconfig] = configs
  1293. all_defconfigs.add(defconfig)
  1294. configs = {}
  1295. elif line[0] == ' ': # CONFIG line
  1296. config, value = line.strip().split('=', 1)
  1297. configs[config] = value
  1298. defconfig_db[config].add(defconfig)
  1299. all_configs.add(config)
  1300. else: # New defconfig
  1301. defconfig = line
  1302. # Work through each target config option in tern, independently
  1303. for config in config_list:
  1304. defconfigs = defconfig_db.get(config)
  1305. if not defconfigs:
  1306. print '%s not found in any defconfig' % config
  1307. continue
  1308. # Get the set of defconfigs without this one (since a config cannot
  1309. # imply itself)
  1310. non_defconfigs = all_defconfigs - defconfigs
  1311. num_defconfigs = len(defconfigs)
  1312. print '%s found in %d/%d defconfigs' % (config, num_defconfigs,
  1313. len(all_configs))
  1314. # This will hold the results: key=config, value=defconfigs containing it
  1315. imply_configs = {}
  1316. rest_configs = all_configs - set([config])
  1317. # Look at every possible config, except the target one
  1318. for imply_config in rest_configs:
  1319. if 'ERRATUM' in imply_config:
  1320. continue
  1321. if not (imply_flags & IMPLY_CMD):
  1322. if 'CONFIG_CMD' in imply_config:
  1323. continue
  1324. if not (imply_flags & IMPLY_TARGET):
  1325. if 'CONFIG_TARGET' in imply_config:
  1326. continue
  1327. # Find set of defconfigs that have this config
  1328. imply_defconfig = defconfig_db[imply_config]
  1329. # Get the intersection of this with defconfigs containing the
  1330. # target config
  1331. common_defconfigs = imply_defconfig & defconfigs
  1332. # Get the set of defconfigs containing this config which DO NOT
  1333. # also contain the taret config. If this set is non-empty it means
  1334. # that this config affects other defconfigs as well as (possibly)
  1335. # the ones affected by the target config. This means it implies
  1336. # things we don't want to imply.
  1337. not_common_defconfigs = imply_defconfig & non_defconfigs
  1338. if not_common_defconfigs:
  1339. continue
  1340. # If there are common defconfigs, imply_config may be useful
  1341. if common_defconfigs:
  1342. skip = False
  1343. if find_superset:
  1344. for prev in imply_configs.keys():
  1345. prev_count = len(imply_configs[prev])
  1346. count = len(common_defconfigs)
  1347. if (prev_count > count and
  1348. (imply_configs[prev] & common_defconfigs ==
  1349. common_defconfigs)):
  1350. # skip imply_config because prev is a superset
  1351. skip = True
  1352. break
  1353. elif count > prev_count:
  1354. # delete prev because imply_config is a superset
  1355. del imply_configs[prev]
  1356. if not skip:
  1357. imply_configs[imply_config] = common_defconfigs
  1358. # Now we have a dict imply_configs of configs which imply each config
  1359. # The value of each dict item is the set of defconfigs containing that
  1360. # config. Rank them so that we print the configs that imply the largest
  1361. # number of defconfigs first.
  1362. ranked_iconfigs = sorted(imply_configs,
  1363. key=lambda k: len(imply_configs[k]), reverse=True)
  1364. kconfig_info = ''
  1365. cwd = os.getcwd()
  1366. add_list = collections.defaultdict(list)
  1367. for iconfig in ranked_iconfigs:
  1368. num_common = len(imply_configs[iconfig])
  1369. # Don't bother if there are less than 5 defconfigs affected.
  1370. if num_common < (2 if imply_flags & IMPLY_MIN_2 else 5):
  1371. continue
  1372. missing = defconfigs - imply_configs[iconfig]
  1373. missing_str = ', '.join(missing) if missing else 'all'
  1374. missing_str = ''
  1375. show = True
  1376. if kconf:
  1377. sym = find_kconfig_rules(kconf, config[CONFIG_LEN:],
  1378. iconfig[CONFIG_LEN:])
  1379. kconfig_info = ''
  1380. if sym:
  1381. locs = sym.get_def_locations()
  1382. if len(locs) == 1:
  1383. fname, linenum = locs[0]
  1384. if cwd and fname.startswith(cwd):
  1385. fname = fname[len(cwd) + 1:]
  1386. kconfig_info = '%s:%d' % (fname, linenum)
  1387. if skip_added:
  1388. show = False
  1389. else:
  1390. sym = kconf.get_symbol(iconfig[CONFIG_LEN:])
  1391. fname = ''
  1392. if sym:
  1393. locs = sym.get_def_locations()
  1394. if len(locs) == 1:
  1395. fname, linenum = locs[0]
  1396. if cwd and fname.startswith(cwd):
  1397. fname = fname[len(cwd) + 1:]
  1398. in_arch_board = not sym or (fname.startswith('arch') or
  1399. fname.startswith('board'))
  1400. if (not in_arch_board and
  1401. not (imply_flags & IMPLY_NON_ARCH_BOARD)):
  1402. continue
  1403. if add_imply and (add_imply == 'all' or
  1404. iconfig in add_imply):
  1405. fname, linenum, kconfig_info = (check_imply_rule(kconf,
  1406. config[CONFIG_LEN:], iconfig[CONFIG_LEN:]))
  1407. if fname:
  1408. add_list[fname].append(linenum)
  1409. if show and kconfig_info != 'skip':
  1410. print '%5d : %-30s%-25s %s' % (num_common, iconfig.ljust(30),
  1411. kconfig_info, missing_str)
  1412. # Having collected a list of things to add, now we add them. We process
  1413. # each file from the largest line number to the smallest so that
  1414. # earlier additions do not affect our line numbers. E.g. if we added an
  1415. # imply at line 20 it would change the position of each line after
  1416. # that.
  1417. for fname, linenums in add_list.iteritems():
  1418. for linenum in sorted(linenums, reverse=True):
  1419. add_imply_rule(config[CONFIG_LEN:], fname, linenum)
  1420. def main():
  1421. try:
  1422. cpu_count = multiprocessing.cpu_count()
  1423. except NotImplementedError:
  1424. cpu_count = 1
  1425. parser = optparse.OptionParser()
  1426. # Add options here
  1427. parser.add_option('-a', '--add-imply', type='string', default='',
  1428. help='comma-separated list of CONFIG options to add '
  1429. "an 'imply' statement to for the CONFIG in -i")
  1430. parser.add_option('-A', '--skip-added', action='store_true', default=False,
  1431. help="don't show options which are already marked as "
  1432. 'implying others')
  1433. parser.add_option('-b', '--build-db', action='store_true', default=False,
  1434. help='build a CONFIG database')
  1435. parser.add_option('-c', '--color', action='store_true', default=False,
  1436. help='display the log in color')
  1437. parser.add_option('-C', '--commit', action='store_true', default=False,
  1438. help='Create a git commit for the operation')
  1439. parser.add_option('-d', '--defconfigs', type='string',
  1440. help='a file containing a list of defconfigs to move, '
  1441. "one per line (for example 'snow_defconfig') "
  1442. "or '-' to read from stdin")
  1443. parser.add_option('-i', '--imply', action='store_true', default=False,
  1444. help='find options which imply others')
  1445. parser.add_option('-I', '--imply-flags', type='string', default='',
  1446. help="control the -i option ('help' for help")
  1447. parser.add_option('-n', '--dry-run', action='store_true', default=False,
  1448. help='perform a trial run (show log with no changes)')
  1449. parser.add_option('-e', '--exit-on-error', action='store_true',
  1450. default=False,
  1451. help='exit immediately on any error')
  1452. parser.add_option('-s', '--force-sync', action='store_true', default=False,
  1453. help='force sync by savedefconfig')
  1454. parser.add_option('-S', '--spl', action='store_true', default=False,
  1455. help='parse config options defined for SPL build')
  1456. parser.add_option('-H', '--headers-only', dest='cleanup_headers_only',
  1457. action='store_true', default=False,
  1458. help='only cleanup the headers')
  1459. parser.add_option('-j', '--jobs', type='int', default=cpu_count,
  1460. help='the number of jobs to run simultaneously')
  1461. parser.add_option('-r', '--git-ref', type='string',
  1462. help='the git ref to clone for building the autoconf.mk')
  1463. parser.add_option('-y', '--yes', action='store_true', default=False,
  1464. help="respond 'yes' to any prompts")
  1465. parser.add_option('-v', '--verbose', action='store_true', default=False,
  1466. help='show any build errors as boards are built')
  1467. parser.usage += ' CONFIG ...'
  1468. (options, configs) = parser.parse_args()
  1469. if len(configs) == 0 and not any((options.force_sync, options.build_db,
  1470. options.imply)):
  1471. parser.print_usage()
  1472. sys.exit(1)
  1473. # prefix the option name with CONFIG_ if missing
  1474. configs = [ config if config.startswith('CONFIG_') else 'CONFIG_' + config
  1475. for config in configs ]
  1476. check_top_directory()
  1477. if options.imply:
  1478. imply_flags = 0
  1479. if options.imply_flags == 'all':
  1480. imply_flags = -1
  1481. elif options.imply_flags:
  1482. for flag in options.imply_flags.split(','):
  1483. bad = flag not in IMPLY_FLAGS
  1484. if bad:
  1485. print "Invalid flag '%s'" % flag
  1486. if flag == 'help' or bad:
  1487. print "Imply flags: (separate with ',')"
  1488. for name, info in IMPLY_FLAGS.iteritems():
  1489. print ' %-15s: %s' % (name, info[1])
  1490. parser.print_usage()
  1491. sys.exit(1)
  1492. imply_flags |= IMPLY_FLAGS[flag][0]
  1493. do_imply_config(configs, options.add_imply, imply_flags,
  1494. options.skip_added)
  1495. return
  1496. config_db = {}
  1497. db_queue = Queue.Queue()
  1498. t = DatabaseThread(config_db, db_queue)
  1499. t.setDaemon(True)
  1500. t.start()
  1501. if not options.cleanup_headers_only:
  1502. check_clean_directory()
  1503. bsettings.Setup('')
  1504. toolchains = toolchain.Toolchains()
  1505. toolchains.GetSettings()
  1506. toolchains.Scan(verbose=False)
  1507. move_config(toolchains, configs, options, db_queue)
  1508. db_queue.join()
  1509. if configs:
  1510. cleanup_headers(configs, options)
  1511. cleanup_extra_options(configs, options)
  1512. cleanup_whitelist(configs, options)
  1513. cleanup_readme(configs, options)
  1514. if options.commit:
  1515. subprocess.call(['git', 'add', '-u'])
  1516. if configs:
  1517. msg = 'Convert %s %sto Kconfig' % (configs[0],
  1518. 'et al ' if len(configs) > 1 else '')
  1519. msg += ('\n\nThis converts the following to Kconfig:\n %s\n' %
  1520. '\n '.join(configs))
  1521. else:
  1522. msg = 'configs: Resync with savedefconfig'
  1523. msg += '\n\nRsync all defconfig files using moveconfig.py'
  1524. subprocess.call(['git', 'commit', '-s', '-m', msg])
  1525. if options.build_db:
  1526. with open(CONFIG_DATABASE, 'w') as fd:
  1527. for defconfig, configs in config_db.iteritems():
  1528. fd.write('%s\n' % defconfig)
  1529. for config in sorted(configs.keys()):
  1530. fd.write(' %s=%s\n' % (config, configs[config]))
  1531. fd.write('\n')
  1532. if __name__ == '__main__':
  1533. main()