checkkconfigsymbols.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  1. #!/usr/bin/env python3
  2. # SPDX-License-Identifier: GPL-2.0-only
  3. """Find Kconfig symbols that are referenced but not defined."""
  4. # (c) 2014-2017 Valentin Rothberg <valentinrothberg@gmail.com>
  5. # (c) 2014 Stefan Hengelein <stefan.hengelein@fau.de>
  6. #
  7. import argparse
  8. import difflib
  9. import os
  10. import re
  11. import signal
  12. import subprocess
  13. import sys
  14. from multiprocessing import Pool, cpu_count
  15. # regex expressions
  16. OPERATORS = r"&|\(|\)|\||\!"
  17. SYMBOL = r"(?:\w*[A-Z0-9]\w*){2,}"
  18. DEF = r"^\s*(?:menu){,1}config\s+(" + SYMBOL + r")\s*"
  19. EXPR = r"(?:" + OPERATORS + r"|\s|" + SYMBOL + r")+"
  20. DEFAULT = r"default\s+.*?(?:if\s.+){,1}"
  21. STMT = r"^\s*(?:if|select|imply|depends\s+on|(?:" + DEFAULT + r"))\s+" + EXPR
  22. SOURCE_SYMBOL = r"(?:\W|\b)+[D]{,1}CONFIG_(" + SYMBOL + r")"
  23. # regex objects
  24. REGEX_FILE_KCONFIG = re.compile(r".*Kconfig[\.\w+\-]*$")
  25. REGEX_SYMBOL = re.compile(r'(?!\B)' + SYMBOL + r'(?!\B)')
  26. REGEX_SOURCE_SYMBOL = re.compile(SOURCE_SYMBOL)
  27. REGEX_KCONFIG_DEF = re.compile(DEF)
  28. REGEX_KCONFIG_EXPR = re.compile(EXPR)
  29. REGEX_KCONFIG_STMT = re.compile(STMT)
  30. REGEX_FILTER_SYMBOLS = re.compile(r"[A-Za-z0-9]$")
  31. REGEX_NUMERIC = re.compile(r"0[xX][0-9a-fA-F]+|[0-9]+")
  32. REGEX_QUOTES = re.compile("(\"(.*?)\")")
  33. def parse_options():
  34. """The user interface of this module."""
  35. usage = "Run this tool to detect Kconfig symbols that are referenced but " \
  36. "not defined in Kconfig. If no option is specified, " \
  37. "checkkconfigsymbols defaults to check your current tree. " \
  38. "Please note that specifying commits will 'git reset --hard\' " \
  39. "your current tree! You may save uncommitted changes to avoid " \
  40. "losing data."
  41. parser = argparse.ArgumentParser(description=usage)
  42. parser.add_argument('-c', '--commit', dest='commit', action='store',
  43. default="",
  44. help="check if the specified commit (hash) introduces "
  45. "undefined Kconfig symbols")
  46. parser.add_argument('-d', '--diff', dest='diff', action='store',
  47. default="",
  48. help="diff undefined symbols between two commits "
  49. "(e.g., -d commmit1..commit2)")
  50. parser.add_argument('-f', '--find', dest='find', action='store_true',
  51. default=False,
  52. help="find and show commits that may cause symbols to be "
  53. "missing (required to run with --diff)")
  54. parser.add_argument('-i', '--ignore', dest='ignore', action='store',
  55. default="",
  56. help="ignore files matching this Python regex "
  57. "(e.g., -i '.*defconfig')")
  58. parser.add_argument('-s', '--sim', dest='sim', action='store', default="",
  59. help="print a list of max. 10 string-similar symbols")
  60. parser.add_argument('--force', dest='force', action='store_true',
  61. default=False,
  62. help="reset current Git tree even when it's dirty")
  63. parser.add_argument('--no-color', dest='color', action='store_false',
  64. default=True,
  65. help="don't print colored output (default when not "
  66. "outputting to a terminal)")
  67. args = parser.parse_args()
  68. if args.commit and args.diff:
  69. sys.exit("Please specify only one option at once.")
  70. if args.diff and not re.match(r"^[\w\-\.\^]+\.\.[\w\-\.\^]+$", args.diff):
  71. sys.exit("Please specify valid input in the following format: "
  72. "\'commit1..commit2\'")
  73. if args.commit or args.diff:
  74. if not args.force and tree_is_dirty():
  75. sys.exit("The current Git tree is dirty (see 'git status'). "
  76. "Running this script may\ndelete important data since it "
  77. "calls 'git reset --hard' for some performance\nreasons. "
  78. " Please run this script in a clean Git tree or pass "
  79. "'--force' if you\nwant to ignore this warning and "
  80. "continue.")
  81. if args.commit:
  82. if args.commit.startswith('HEAD'):
  83. sys.exit("The --commit option can't use the HEAD ref")
  84. args.find = False
  85. if args.ignore:
  86. try:
  87. re.match(args.ignore, "this/is/just/a/test.c")
  88. except:
  89. sys.exit("Please specify a valid Python regex.")
  90. return args
  91. def print_undefined_symbols():
  92. """Main function of this module."""
  93. args = parse_options()
  94. global COLOR
  95. COLOR = args.color and sys.stdout.isatty()
  96. if args.sim and not args.commit and not args.diff:
  97. sims = find_sims(args.sim, args.ignore)
  98. if sims:
  99. print("%s: %s" % (yel("Similar symbols"), ', '.join(sims)))
  100. else:
  101. print("%s: no similar symbols found" % yel("Similar symbols"))
  102. sys.exit(0)
  103. # dictionary of (un)defined symbols
  104. defined = {}
  105. undefined = {}
  106. if args.commit or args.diff:
  107. head = get_head()
  108. # get commit range
  109. commit_a = None
  110. commit_b = None
  111. if args.commit:
  112. commit_a = args.commit + "~"
  113. commit_b = args.commit
  114. elif args.diff:
  115. split = args.diff.split("..")
  116. commit_a = split[0]
  117. commit_b = split[1]
  118. undefined_a = {}
  119. undefined_b = {}
  120. # get undefined items before the commit
  121. reset(commit_a)
  122. undefined_a, _ = check_symbols(args.ignore)
  123. # get undefined items for the commit
  124. reset(commit_b)
  125. undefined_b, defined = check_symbols(args.ignore)
  126. # report cases that are present for the commit but not before
  127. for symbol in sorted(undefined_b):
  128. # symbol has not been undefined before
  129. if symbol not in undefined_a:
  130. files = sorted(undefined_b.get(symbol))
  131. undefined[symbol] = files
  132. # check if there are new files that reference the undefined symbol
  133. else:
  134. files = sorted(undefined_b.get(symbol) -
  135. undefined_a.get(symbol))
  136. if files:
  137. undefined[symbol] = files
  138. # reset to head
  139. reset(head)
  140. # default to check the entire tree
  141. else:
  142. undefined, defined = check_symbols(args.ignore)
  143. # now print the output
  144. for symbol in sorted(undefined):
  145. print(red(symbol))
  146. files = sorted(undefined.get(symbol))
  147. print("%s: %s" % (yel("Referencing files"), ", ".join(files)))
  148. sims = find_sims(symbol, args.ignore, defined)
  149. sims_out = yel("Similar symbols")
  150. if sims:
  151. print("%s: %s" % (sims_out, ', '.join(sims)))
  152. else:
  153. print("%s: %s" % (sims_out, "no similar symbols found"))
  154. if args.find:
  155. print("%s:" % yel("Commits changing symbol"))
  156. commits = find_commits(symbol, args.diff)
  157. if commits:
  158. for commit in commits:
  159. commit = commit.split(" ", 1)
  160. print("\t- %s (\"%s\")" % (yel(commit[0]), commit[1]))
  161. else:
  162. print("\t- no commit found")
  163. print() # new line
  164. def reset(commit):
  165. """Reset current git tree to %commit."""
  166. execute(["git", "reset", "--hard", commit])
  167. def yel(string):
  168. """
  169. Color %string yellow.
  170. """
  171. return "\033[33m%s\033[0m" % string if COLOR else string
  172. def red(string):
  173. """
  174. Color %string red.
  175. """
  176. return "\033[31m%s\033[0m" % string if COLOR else string
  177. def execute(cmd):
  178. """Execute %cmd and return stdout. Exit in case of error."""
  179. try:
  180. stdout = subprocess.check_output(cmd, stderr=subprocess.STDOUT, shell=False)
  181. stdout = stdout.decode(errors='replace')
  182. except subprocess.CalledProcessError as fail:
  183. exit(fail)
  184. return stdout
  185. def find_commits(symbol, diff):
  186. """Find commits changing %symbol in the given range of %diff."""
  187. commits = execute(["git", "log", "--pretty=oneline",
  188. "--abbrev-commit", "-G",
  189. symbol, diff])
  190. return [x for x in commits.split("\n") if x]
  191. def tree_is_dirty():
  192. """Return true if the current working tree is dirty (i.e., if any file has
  193. been added, deleted, modified, renamed or copied but not committed)."""
  194. stdout = execute(["git", "status", "--porcelain"])
  195. for line in stdout:
  196. if re.findall(r"[URMADC]{1}", line[:2]):
  197. return True
  198. return False
  199. def get_head():
  200. """Return commit hash of current HEAD."""
  201. stdout = execute(["git", "rev-parse", "HEAD"])
  202. return stdout.strip('\n')
  203. def partition(lst, size):
  204. """Partition list @lst into eveni-sized lists of size @size."""
  205. return [lst[i::size] for i in range(size)]
  206. def init_worker():
  207. """Set signal handler to ignore SIGINT."""
  208. signal.signal(signal.SIGINT, signal.SIG_IGN)
  209. def find_sims(symbol, ignore, defined=[]):
  210. """Return a list of max. ten Kconfig symbols that are string-similar to
  211. @symbol."""
  212. if defined:
  213. return difflib.get_close_matches(symbol, set(defined), 10)
  214. pool = Pool(cpu_count(), init_worker)
  215. kfiles = []
  216. for gitfile in get_files():
  217. if REGEX_FILE_KCONFIG.match(gitfile):
  218. kfiles.append(gitfile)
  219. arglist = []
  220. for part in partition(kfiles, cpu_count()):
  221. arglist.append((part, ignore))
  222. for res in pool.map(parse_kconfig_files, arglist):
  223. defined.extend(res[0])
  224. return difflib.get_close_matches(symbol, set(defined), 10)
  225. def get_files():
  226. """Return a list of all files in the current git directory."""
  227. # use 'git ls-files' to get the worklist
  228. stdout = execute(["git", "ls-files"])
  229. if len(stdout) > 0 and stdout[-1] == "\n":
  230. stdout = stdout[:-1]
  231. files = []
  232. for gitfile in stdout.rsplit("\n"):
  233. if ".git" in gitfile or "ChangeLog" in gitfile or \
  234. ".log" in gitfile or os.path.isdir(gitfile) or \
  235. gitfile.startswith("tools/"):
  236. continue
  237. files.append(gitfile)
  238. return files
  239. def check_symbols(ignore):
  240. """Find undefined Kconfig symbols and return a dict with the symbol as key
  241. and a list of referencing files as value. Files matching %ignore are not
  242. checked for undefined symbols."""
  243. pool = Pool(cpu_count(), init_worker)
  244. try:
  245. return check_symbols_helper(pool, ignore)
  246. except KeyboardInterrupt:
  247. pool.terminate()
  248. pool.join()
  249. sys.exit(1)
  250. def check_symbols_helper(pool, ignore):
  251. """Helper method for check_symbols(). Used to catch keyboard interrupts in
  252. check_symbols() in order to properly terminate running worker processes."""
  253. source_files = []
  254. kconfig_files = []
  255. defined_symbols = []
  256. referenced_symbols = dict() # {file: [symbols]}
  257. for gitfile in get_files():
  258. if REGEX_FILE_KCONFIG.match(gitfile):
  259. kconfig_files.append(gitfile)
  260. else:
  261. if ignore and re.match(ignore, gitfile):
  262. continue
  263. # add source files that do not match the ignore pattern
  264. source_files.append(gitfile)
  265. # parse source files
  266. arglist = partition(source_files, cpu_count())
  267. for res in pool.map(parse_source_files, arglist):
  268. referenced_symbols.update(res)
  269. # parse kconfig files
  270. arglist = []
  271. for part in partition(kconfig_files, cpu_count()):
  272. arglist.append((part, ignore))
  273. for res in pool.map(parse_kconfig_files, arglist):
  274. defined_symbols.extend(res[0])
  275. referenced_symbols.update(res[1])
  276. defined_symbols = set(defined_symbols)
  277. # inverse mapping of referenced_symbols to dict(symbol: [files])
  278. inv_map = dict()
  279. for _file, symbols in referenced_symbols.items():
  280. for symbol in symbols:
  281. inv_map[symbol] = inv_map.get(symbol, set())
  282. inv_map[symbol].add(_file)
  283. referenced_symbols = inv_map
  284. undefined = {} # {symbol: [files]}
  285. for symbol in sorted(referenced_symbols):
  286. # filter some false positives
  287. if symbol == "FOO" or symbol == "BAR" or \
  288. symbol == "FOO_BAR" or symbol == "XXX":
  289. continue
  290. if symbol not in defined_symbols:
  291. if symbol.endswith("_MODULE"):
  292. # avoid false positives for kernel modules
  293. if symbol[:-len("_MODULE")] in defined_symbols:
  294. continue
  295. undefined[symbol] = referenced_symbols.get(symbol)
  296. return undefined, defined_symbols
  297. def parse_source_files(source_files):
  298. """Parse each source file in @source_files and return dictionary with source
  299. files as keys and lists of references Kconfig symbols as values."""
  300. referenced_symbols = dict()
  301. for sfile in source_files:
  302. referenced_symbols[sfile] = parse_source_file(sfile)
  303. return referenced_symbols
  304. def parse_source_file(sfile):
  305. """Parse @sfile and return a list of referenced Kconfig symbols."""
  306. lines = []
  307. references = []
  308. if not os.path.exists(sfile):
  309. return references
  310. with open(sfile, "r", encoding='utf-8', errors='replace') as stream:
  311. lines = stream.readlines()
  312. for line in lines:
  313. if "CONFIG_" not in line:
  314. continue
  315. symbols = REGEX_SOURCE_SYMBOL.findall(line)
  316. for symbol in symbols:
  317. if not REGEX_FILTER_SYMBOLS.search(symbol):
  318. continue
  319. references.append(symbol)
  320. return references
  321. def get_symbols_in_line(line):
  322. """Return mentioned Kconfig symbols in @line."""
  323. return REGEX_SYMBOL.findall(line)
  324. def parse_kconfig_files(args):
  325. """Parse kconfig files and return tuple of defined and references Kconfig
  326. symbols. Note, @args is a tuple of a list of files and the @ignore
  327. pattern."""
  328. kconfig_files = args[0]
  329. ignore = args[1]
  330. defined_symbols = []
  331. referenced_symbols = dict()
  332. for kfile in kconfig_files:
  333. defined, references = parse_kconfig_file(kfile)
  334. defined_symbols.extend(defined)
  335. if ignore and re.match(ignore, kfile):
  336. # do not collect references for files that match the ignore pattern
  337. continue
  338. referenced_symbols[kfile] = references
  339. return (defined_symbols, referenced_symbols)
  340. def parse_kconfig_file(kfile):
  341. """Parse @kfile and update symbol definitions and references."""
  342. lines = []
  343. defined = []
  344. references = []
  345. if not os.path.exists(kfile):
  346. return defined, references
  347. with open(kfile, "r", encoding='utf-8', errors='replace') as stream:
  348. lines = stream.readlines()
  349. for i in range(len(lines)):
  350. line = lines[i]
  351. line = line.strip('\n')
  352. line = line.split("#")[0] # ignore comments
  353. if REGEX_KCONFIG_DEF.match(line):
  354. symbol_def = REGEX_KCONFIG_DEF.findall(line)
  355. defined.append(symbol_def[0])
  356. elif REGEX_KCONFIG_STMT.match(line):
  357. line = REGEX_QUOTES.sub("", line)
  358. symbols = get_symbols_in_line(line)
  359. # multi-line statements
  360. while line.endswith("\\"):
  361. i += 1
  362. line = lines[i]
  363. line = line.strip('\n')
  364. symbols.extend(get_symbols_in_line(line))
  365. for symbol in set(symbols):
  366. if REGEX_NUMERIC.match(symbol):
  367. # ignore numeric values
  368. continue
  369. references.append(symbol)
  370. return defined, references
  371. def main():
  372. try:
  373. print_undefined_symbols()
  374. except BrokenPipeError:
  375. # Python flushes standard streams on exit; redirect remaining output
  376. # to devnull to avoid another BrokenPipeError at shutdown
  377. devnull = os.open(os.devnull, os.O_WRONLY)
  378. os.dup2(devnull, sys.stdout.fileno())
  379. sys.exit(1) # Python exits with error code 1 on EPIPE
  380. if __name__ == "__main__":
  381. main()