checkkconfigsymbols.py 16 KB

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