checkkconfigsymbols.py 11 KB

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