checkkconfigsymbols.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. #!/usr/bin/env python2
  2. """Find Kconfig symbols that are referenced but not defined."""
  3. # (c) 2014-2015 Valentin Rothberg <Valentin.Rothberg@lip6.fr>
  4. # (c) 2014 Stefan Hengelein <stefan.hengelein@fau.de>
  5. #
  6. # Licensed under the terms of the GNU GPL License version 2
  7. import os
  8. import re
  9. import sys
  10. from subprocess import Popen, PIPE, STDOUT
  11. from optparse import OptionParser
  12. # regex expressions
  13. OPERATORS = r"&|\(|\)|\||\!"
  14. FEATURE = r"(?:\w*[A-Z0-9]\w*){2,}"
  15. DEF = r"^\s*(?:menu){,1}config\s+(" + FEATURE + r")\s*"
  16. EXPR = r"(?:" + OPERATORS + r"|\s|" + FEATURE + r")+"
  17. STMT = r"^\s*(?:if|select|depends\s+on)\s+" + EXPR
  18. SOURCE_FEATURE = r"(?:\W|\b)+[D]{,1}CONFIG_(" + FEATURE + r")"
  19. # regex objects
  20. REGEX_FILE_KCONFIG = re.compile(r".*Kconfig[\.\w+\-]*$")
  21. REGEX_FEATURE = re.compile(r"(" + FEATURE + r")")
  22. REGEX_SOURCE_FEATURE = re.compile(SOURCE_FEATURE)
  23. REGEX_KCONFIG_DEF = re.compile(DEF)
  24. REGEX_KCONFIG_EXPR = re.compile(EXPR)
  25. REGEX_KCONFIG_STMT = re.compile(STMT)
  26. REGEX_KCONFIG_HELP = re.compile(r"^\s+(help|---help---)\s*$")
  27. REGEX_FILTER_FEATURES = re.compile(r"[A-Za-z0-9]$")
  28. def parse_options():
  29. """The user interface of this module."""
  30. usage = "%prog [options]\n\n" \
  31. "Run this tool to detect Kconfig symbols that are referenced but " \
  32. "not defined in\nKconfig. The output of this tool has the " \
  33. "format \'Undefined symbol\\tFile list\'\n\n" \
  34. "If no option is specified, %prog will default to check your\n" \
  35. "current tree. Please note that specifying commits will " \
  36. "\'git reset --hard\'\nyour current tree! You may save " \
  37. "uncommitted changes to avoid losing data."
  38. parser = OptionParser(usage=usage)
  39. parser.add_option('-c', '--commit', dest='commit', action='store',
  40. default="",
  41. help="Check if the specified commit (hash) introduces "
  42. "undefined Kconfig symbols.")
  43. parser.add_option('-d', '--diff', dest='diff', action='store',
  44. default="",
  45. help="Diff undefined symbols between two commits. The "
  46. "input format bases on Git log's "
  47. "\'commmit1..commit2\'.")
  48. parser.add_option('-f', '--find', dest='find', action='store_true',
  49. default=False,
  50. help="Find and show commits that may cause symbols to be "
  51. "missing. Required to run with --diff.")
  52. parser.add_option('-i', '--ignore', dest='ignore', action='store',
  53. default="",
  54. help="Ignore files matching this pattern. Note that "
  55. "the pattern needs to be a Python regex. To "
  56. "ignore defconfigs, specify -i '.*defconfig'.")
  57. parser.add_option('', '--force', dest='force', action='store_true',
  58. default=False,
  59. help="Reset current Git tree even when it's dirty.")
  60. (opts, _) = parser.parse_args()
  61. if opts.commit and opts.diff:
  62. sys.exit("Please specify only one option at once.")
  63. if opts.diff and not re.match(r"^[\w\-\.]+\.\.[\w\-\.]+$", opts.diff):
  64. sys.exit("Please specify valid input in the following format: "
  65. "\'commmit1..commit2\'")
  66. if opts.commit or opts.diff:
  67. if not opts.force and tree_is_dirty():
  68. sys.exit("The current Git tree is dirty (see 'git status'). "
  69. "Running this script may\ndelete important data since it "
  70. "calls 'git reset --hard' for some performance\nreasons. "
  71. " Please run this script in a clean Git tree or pass "
  72. "'--force' if you\nwant to ignore this warning and "
  73. "continue.")
  74. if opts.commit:
  75. opts.find = False
  76. if opts.ignore:
  77. try:
  78. re.match(opts.ignore, "this/is/just/a/test.c")
  79. except:
  80. sys.exit("Please specify a valid Python regex.")
  81. return opts
  82. def main():
  83. """Main function of this module."""
  84. opts = parse_options()
  85. if opts.commit or opts.diff:
  86. head = get_head()
  87. # get commit range
  88. commit_a = None
  89. commit_b = None
  90. if opts.commit:
  91. commit_a = opts.commit + "~"
  92. commit_b = opts.commit
  93. elif opts.diff:
  94. split = opts.diff.split("..")
  95. commit_a = split[0]
  96. commit_b = split[1]
  97. undefined_a = {}
  98. undefined_b = {}
  99. # get undefined items before the commit
  100. execute("git reset --hard %s" % commit_a)
  101. undefined_a = check_symbols(opts.ignore)
  102. # get undefined items for the commit
  103. execute("git reset --hard %s" % commit_b)
  104. undefined_b = check_symbols(opts.ignore)
  105. # report cases that are present for the commit but not before
  106. for feature in sorted(undefined_b):
  107. # feature has not been undefined before
  108. if not feature in undefined_a:
  109. files = sorted(undefined_b.get(feature))
  110. print "%s\t%s" % (feature, ", ".join(files))
  111. if opts.find:
  112. commits = find_commits(feature, opts.diff)
  113. print commits
  114. # check if there are new files that reference the undefined feature
  115. else:
  116. files = sorted(undefined_b.get(feature) -
  117. undefined_a.get(feature))
  118. if files:
  119. print "%s\t%s" % (feature, ", ".join(files))
  120. if opts.find:
  121. commits = find_commits(feature, opts.diff)
  122. print commits
  123. # reset to head
  124. execute("git reset --hard %s" % head)
  125. # default to check the entire tree
  126. else:
  127. undefined = check_symbols(opts.ignore)
  128. for feature in sorted(undefined):
  129. files = sorted(undefined.get(feature))
  130. print "%s\t%s" % (feature, ", ".join(files))
  131. def execute(cmd):
  132. """Execute %cmd and return stdout. Exit in case of error."""
  133. pop = Popen(cmd, stdout=PIPE, stderr=STDOUT, shell=True)
  134. (stdout, _) = pop.communicate() # wait until finished
  135. if pop.returncode != 0:
  136. sys.exit(stdout)
  137. return stdout
  138. def find_commits(symbol, diff):
  139. """Find commits changing %symbol in the given range of %diff."""
  140. commits = execute("git log --pretty=oneline --abbrev-commit -G %s %s"
  141. % (symbol, diff))
  142. return commits
  143. def tree_is_dirty():
  144. """Return true if the current working tree is dirty (i.e., if any file has
  145. been added, deleted, modified, renamed or copied but not committed)."""
  146. stdout = execute("git status --porcelain")
  147. for line in stdout:
  148. if re.findall(r"[URMADC]{1}", line[:2]):
  149. return True
  150. return False
  151. def get_head():
  152. """Return commit hash of current HEAD."""
  153. stdout = execute("git rev-parse HEAD")
  154. return stdout.strip('\n')
  155. def check_symbols(ignore):
  156. """Find undefined Kconfig symbols and return a dict with the symbol as key
  157. and a list of referencing files as value. Files matching %ignore are not
  158. checked for undefined symbols."""
  159. source_files = []
  160. kconfig_files = []
  161. defined_features = set()
  162. referenced_features = dict() # {feature: [files]}
  163. # use 'git ls-files' to get the worklist
  164. stdout = execute("git ls-files")
  165. if len(stdout) > 0 and stdout[-1] == "\n":
  166. stdout = stdout[:-1]
  167. for gitfile in stdout.rsplit("\n"):
  168. if ".git" in gitfile or "ChangeLog" in gitfile or \
  169. ".log" in gitfile or os.path.isdir(gitfile) or \
  170. gitfile.startswith("tools/"):
  171. continue
  172. if REGEX_FILE_KCONFIG.match(gitfile):
  173. kconfig_files.append(gitfile)
  174. else:
  175. # all non-Kconfig files are checked for consistency
  176. source_files.append(gitfile)
  177. for sfile in source_files:
  178. if ignore and re.match(ignore, sfile):
  179. # do not check files matching %ignore
  180. continue
  181. parse_source_file(sfile, referenced_features)
  182. for kfile in kconfig_files:
  183. if ignore and re.match(ignore, kfile):
  184. # do not collect references for files matching %ignore
  185. parse_kconfig_file(kfile, defined_features, dict())
  186. else:
  187. parse_kconfig_file(kfile, defined_features, referenced_features)
  188. undefined = {} # {feature: [files]}
  189. for feature in sorted(referenced_features):
  190. # filter some false positives
  191. if feature == "FOO" or feature == "BAR" or \
  192. feature == "FOO_BAR" or feature == "XXX":
  193. continue
  194. if feature not in defined_features:
  195. if feature.endswith("_MODULE"):
  196. # avoid false positives for kernel modules
  197. if feature[:-len("_MODULE")] in defined_features:
  198. continue
  199. undefined[feature] = referenced_features.get(feature)
  200. return undefined
  201. def parse_source_file(sfile, referenced_features):
  202. """Parse @sfile for referenced Kconfig features."""
  203. lines = []
  204. with open(sfile, "r") as stream:
  205. lines = stream.readlines()
  206. for line in lines:
  207. if not "CONFIG_" in line:
  208. continue
  209. features = REGEX_SOURCE_FEATURE.findall(line)
  210. for feature in features:
  211. if not REGEX_FILTER_FEATURES.search(feature):
  212. continue
  213. sfiles = referenced_features.get(feature, set())
  214. sfiles.add(sfile)
  215. referenced_features[feature] = sfiles
  216. def get_features_in_line(line):
  217. """Return mentioned Kconfig features in @line."""
  218. return REGEX_FEATURE.findall(line)
  219. def parse_kconfig_file(kfile, defined_features, referenced_features):
  220. """Parse @kfile and update feature definitions and references."""
  221. lines = []
  222. skip = False
  223. with open(kfile, "r") as stream:
  224. lines = stream.readlines()
  225. for i in range(len(lines)):
  226. line = lines[i]
  227. line = line.strip('\n')
  228. line = line.split("#")[0] # ignore comments
  229. if REGEX_KCONFIG_DEF.match(line):
  230. feature_def = REGEX_KCONFIG_DEF.findall(line)
  231. defined_features.add(feature_def[0])
  232. skip = False
  233. elif REGEX_KCONFIG_HELP.match(line):
  234. skip = True
  235. elif skip:
  236. # ignore content of help messages
  237. pass
  238. elif REGEX_KCONFIG_STMT.match(line):
  239. features = get_features_in_line(line)
  240. # multi-line statements
  241. while line.endswith("\\"):
  242. i += 1
  243. line = lines[i]
  244. line = line.strip('\n')
  245. features.extend(get_features_in_line(line))
  246. for feature in set(features):
  247. paths = referenced_features.get(feature, set())
  248. paths.add(kfile)
  249. referenced_features[feature] = paths
  250. if __name__ == "__main__":
  251. main()