checkkconfigsymbols.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  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. (opts, _) = parser.parse_args()
  69. if opts.commit and opts.diff:
  70. sys.exit("Please specify only one option at once.")
  71. if opts.diff and not re.match(r"^[\w\-\.]+\.\.[\w\-\.]+$", opts.diff):
  72. sys.exit("Please specify valid input in the following format: "
  73. "\'commit1..commit2\'")
  74. if opts.commit or opts.diff:
  75. if not opts.force and tree_is_dirty():
  76. sys.exit("The current Git tree is dirty (see 'git status'). "
  77. "Running this script may\ndelete important data since it "
  78. "calls 'git reset --hard' for some performance\nreasons. "
  79. " Please run this script in a clean Git tree or pass "
  80. "'--force' if you\nwant to ignore this warning and "
  81. "continue.")
  82. if opts.commit:
  83. opts.find = False
  84. if opts.ignore:
  85. try:
  86. re.match(opts.ignore, "this/is/just/a/test.c")
  87. except:
  88. sys.exit("Please specify a valid Python regex.")
  89. return opts
  90. def main():
  91. """Main function of this module."""
  92. opts = parse_options()
  93. if opts.sim and not opts.commit and not opts.diff:
  94. sims = find_sims(opts.sim, opts.ignore)
  95. if sims:
  96. print "%s: %s" % (yel("Similar symbols"), ', '.join(sims))
  97. else:
  98. print "%s: no similar symbols found" % yel("Similar symbols")
  99. sys.exit(0)
  100. # dictionary of (un)defined symbols
  101. defined = {}
  102. undefined = {}
  103. if opts.commit or opts.diff:
  104. head = get_head()
  105. # get commit range
  106. commit_a = None
  107. commit_b = None
  108. if opts.commit:
  109. commit_a = opts.commit + "~"
  110. commit_b = opts.commit
  111. elif opts.diff:
  112. split = opts.diff.split("..")
  113. commit_a = split[0]
  114. commit_b = split[1]
  115. undefined_a = {}
  116. undefined_b = {}
  117. # get undefined items before the commit
  118. execute("git reset --hard %s" % commit_a)
  119. undefined_a, _ = check_symbols(opts.ignore)
  120. # get undefined items for the commit
  121. execute("git reset --hard %s" % commit_b)
  122. undefined_b, defined = check_symbols(opts.ignore)
  123. # report cases that are present for the commit but not before
  124. for feature in sorted(undefined_b):
  125. # feature has not been undefined before
  126. if not feature in undefined_a:
  127. files = sorted(undefined_b.get(feature))
  128. undefined[feature] = files
  129. # check if there are new files that reference the undefined feature
  130. else:
  131. files = sorted(undefined_b.get(feature) -
  132. undefined_a.get(feature))
  133. if files:
  134. undefined[feature] = files
  135. # reset to head
  136. execute("git reset --hard %s" % head)
  137. # default to check the entire tree
  138. else:
  139. undefined, defined = check_symbols(opts.ignore)
  140. # now print the output
  141. for feature in sorted(undefined):
  142. print red(feature)
  143. files = sorted(undefined.get(feature))
  144. print "%s: %s" % (yel("Referencing files"), ", ".join(files))
  145. sims = find_sims(feature, opts.ignore, defined)
  146. sims_out = yel("Similar symbols")
  147. if sims:
  148. print "%s: %s" % (sims_out, ', '.join(sims))
  149. else:
  150. print "%s: %s" % (sims_out, "no similar symbols found")
  151. if opts.find:
  152. print "%s:" % yel("Commits changing symbol")
  153. commits = find_commits(feature, opts.diff)
  154. if commits:
  155. for commit in commits:
  156. commit = commit.split(" ", 1)
  157. print "\t- %s (\"%s\")" % (yel(commit[0]), commit[1])
  158. else:
  159. print "\t- no commit found"
  160. print # new line
  161. def yel(string):
  162. """
  163. Color %string yellow.
  164. """
  165. return "\033[33m%s\033[0m" % string
  166. def red(string):
  167. """
  168. Color %string red.
  169. """
  170. return "\033[31m%s\033[0m" % string
  171. def execute(cmd):
  172. """Execute %cmd and return stdout. Exit in case of error."""
  173. pop = Popen(cmd, stdout=PIPE, stderr=STDOUT, shell=True)
  174. (stdout, _) = pop.communicate() # wait until finished
  175. if pop.returncode != 0:
  176. sys.exit(stdout)
  177. return stdout
  178. def find_commits(symbol, diff):
  179. """Find commits changing %symbol in the given range of %diff."""
  180. commits = execute("git log --pretty=oneline --abbrev-commit -G %s %s"
  181. % (symbol, diff))
  182. return [x for x in commits.split("\n") if x]
  183. def tree_is_dirty():
  184. """Return true if the current working tree is dirty (i.e., if any file has
  185. been added, deleted, modified, renamed or copied but not committed)."""
  186. stdout = execute("git status --porcelain")
  187. for line in stdout:
  188. if re.findall(r"[URMADC]{1}", line[:2]):
  189. return True
  190. return False
  191. def get_head():
  192. """Return commit hash of current HEAD."""
  193. stdout = execute("git rev-parse HEAD")
  194. return stdout.strip('\n')
  195. def partition(lst, size):
  196. """Partition list @lst into eveni-sized lists of size @size."""
  197. return [lst[i::size] for i in xrange(size)]
  198. def init_worker():
  199. """Set signal handler to ignore SIGINT."""
  200. signal.signal(signal.SIGINT, signal.SIG_IGN)
  201. def find_sims(symbol, ignore, defined = []):
  202. """Return a list of max. ten Kconfig symbols that are string-similar to
  203. @symbol."""
  204. if defined:
  205. return sorted(difflib.get_close_matches(symbol, set(defined), 10))
  206. pool = Pool(cpu_count(), init_worker)
  207. kfiles = []
  208. for gitfile in get_files():
  209. if REGEX_FILE_KCONFIG.match(gitfile):
  210. kfiles.append(gitfile)
  211. arglist = []
  212. for part in partition(kfiles, cpu_count()):
  213. arglist.append((part, ignore))
  214. for res in pool.map(parse_kconfig_files, arglist):
  215. defined.extend(res[0])
  216. return sorted(difflib.get_close_matches(symbol, set(defined), 10))
  217. def get_files():
  218. """Return a list of all files in the current git directory."""
  219. # use 'git ls-files' to get the worklist
  220. stdout = execute("git ls-files")
  221. if len(stdout) > 0 and stdout[-1] == "\n":
  222. stdout = stdout[:-1]
  223. files = []
  224. for gitfile in stdout.rsplit("\n"):
  225. if ".git" in gitfile or "ChangeLog" in gitfile or \
  226. ".log" in gitfile or os.path.isdir(gitfile) or \
  227. gitfile.startswith("tools/"):
  228. continue
  229. files.append(gitfile)
  230. return files
  231. def check_symbols(ignore):
  232. """Find undefined Kconfig symbols and return a dict with the symbol as key
  233. and a list of referencing files as value. Files matching %ignore are not
  234. checked for undefined symbols."""
  235. pool = Pool(cpu_count(), init_worker)
  236. try:
  237. return check_symbols_helper(pool, ignore)
  238. except KeyboardInterrupt:
  239. pool.terminate()
  240. pool.join()
  241. sys.exit(1)
  242. def check_symbols_helper(pool, ignore):
  243. """Helper method for check_symbols(). Used to catch keyboard interrupts in
  244. check_symbols() in order to properly terminate running worker processes."""
  245. source_files = []
  246. kconfig_files = []
  247. defined_features = []
  248. referenced_features = dict() # {file: [features]}
  249. for gitfile in get_files():
  250. if REGEX_FILE_KCONFIG.match(gitfile):
  251. kconfig_files.append(gitfile)
  252. else:
  253. if ignore and not re.match(ignore, gitfile):
  254. continue
  255. # add source files that do not match the ignore pattern
  256. source_files.append(gitfile)
  257. # parse source files
  258. arglist = partition(source_files, cpu_count())
  259. for res in pool.map(parse_source_files, arglist):
  260. referenced_features.update(res)
  261. # parse kconfig files
  262. arglist = []
  263. for part in partition(kconfig_files, cpu_count()):
  264. arglist.append((part, ignore))
  265. for res in pool.map(parse_kconfig_files, arglist):
  266. defined_features.extend(res[0])
  267. referenced_features.update(res[1])
  268. defined_features = set(defined_features)
  269. # inverse mapping of referenced_features to dict(feature: [files])
  270. inv_map = dict()
  271. for _file, features in referenced_features.iteritems():
  272. for feature in features:
  273. inv_map[feature] = inv_map.get(feature, set())
  274. inv_map[feature].add(_file)
  275. referenced_features = inv_map
  276. undefined = {} # {feature: [files]}
  277. for feature in sorted(referenced_features):
  278. # filter some false positives
  279. if feature == "FOO" or feature == "BAR" or \
  280. feature == "FOO_BAR" or feature == "XXX":
  281. continue
  282. if feature not in defined_features:
  283. if feature.endswith("_MODULE"):
  284. # avoid false positives for kernel modules
  285. if feature[:-len("_MODULE")] in defined_features:
  286. continue
  287. undefined[feature] = referenced_features.get(feature)
  288. return undefined, defined_features
  289. def parse_source_files(source_files):
  290. """Parse each source file in @source_files and return dictionary with source
  291. files as keys and lists of references Kconfig symbols as values."""
  292. referenced_features = dict()
  293. for sfile in source_files:
  294. referenced_features[sfile] = parse_source_file(sfile)
  295. return referenced_features
  296. def parse_source_file(sfile):
  297. """Parse @sfile and return a list of referenced Kconfig features."""
  298. lines = []
  299. references = []
  300. if not os.path.exists(sfile):
  301. return references
  302. with open(sfile, "r") as stream:
  303. lines = stream.readlines()
  304. for line in lines:
  305. if not "CONFIG_" in line:
  306. continue
  307. features = REGEX_SOURCE_FEATURE.findall(line)
  308. for feature in features:
  309. if not REGEX_FILTER_FEATURES.search(feature):
  310. continue
  311. references.append(feature)
  312. return references
  313. def get_features_in_line(line):
  314. """Return mentioned Kconfig features in @line."""
  315. return REGEX_FEATURE.findall(line)
  316. def parse_kconfig_files(args):
  317. """Parse kconfig files and return tuple of defined and references Kconfig
  318. symbols. Note, @args is a tuple of a list of files and the @ignore
  319. pattern."""
  320. kconfig_files = args[0]
  321. ignore = args[1]
  322. defined_features = []
  323. referenced_features = dict()
  324. for kfile in kconfig_files:
  325. defined, references = parse_kconfig_file(kfile)
  326. defined_features.extend(defined)
  327. if ignore and re.match(ignore, kfile):
  328. # do not collect references for files that match the ignore pattern
  329. continue
  330. referenced_features[kfile] = references
  331. return (defined_features, referenced_features)
  332. def parse_kconfig_file(kfile):
  333. """Parse @kfile and update feature definitions and references."""
  334. lines = []
  335. defined = []
  336. references = []
  337. skip = False
  338. if not os.path.exists(kfile):
  339. return defined, references
  340. with open(kfile, "r") as stream:
  341. lines = stream.readlines()
  342. for i in range(len(lines)):
  343. line = lines[i]
  344. line = line.strip('\n')
  345. line = line.split("#")[0] # ignore comments
  346. if REGEX_KCONFIG_DEF.match(line):
  347. feature_def = REGEX_KCONFIG_DEF.findall(line)
  348. defined.append(feature_def[0])
  349. skip = False
  350. elif REGEX_KCONFIG_HELP.match(line):
  351. skip = True
  352. elif skip:
  353. # ignore content of help messages
  354. pass
  355. elif REGEX_KCONFIG_STMT.match(line):
  356. line = REGEX_QUOTES.sub("", line)
  357. features = get_features_in_line(line)
  358. # multi-line statements
  359. while line.endswith("\\"):
  360. i += 1
  361. line = lines[i]
  362. line = line.strip('\n')
  363. features.extend(get_features_in_line(line))
  364. for feature in set(features):
  365. if REGEX_NUMERIC.match(feature):
  366. # ignore numeric values
  367. continue
  368. references.append(feature)
  369. return defined, references
  370. if __name__ == "__main__":
  371. main()