checkkconfigsymbols.py 16 KB

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