moveconfig.py 58 KB

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