checkkconfigsymbols.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  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('-i', '--ignore', dest='ignore', action='store',
  49. default="",
  50. help="Ignore files matching this pattern. Note that "
  51. "the pattern needs to be a Python regex. To "
  52. "ignore defconfigs, specify -i '.*defconfig'.")
  53. parser.add_option('', '--force', dest='force', action='store_true',
  54. default=False,
  55. help="Reset current Git tree even when it's dirty.")
  56. (opts, _) = parser.parse_args()
  57. if opts.commit and opts.diff:
  58. sys.exit("Please specify only one option at once.")
  59. if opts.diff and not re.match(r"^[\w\-\.]+\.\.[\w\-\.]+$", opts.diff):
  60. sys.exit("Please specify valid input in the following format: "
  61. "\'commmit1..commit2\'")
  62. if opts.commit or opts.diff:
  63. if not opts.force and tree_is_dirty():
  64. sys.exit("The current Git tree is dirty (see 'git status'). "
  65. "Running this script may\ndelete important data since it "
  66. "calls 'git reset --hard' for some performance\nreasons. "
  67. " Please run this script in a clean Git tree or pass "
  68. "'--force' if you\nwant to ignore this warning and "
  69. "continue.")
  70. if opts.ignore:
  71. try:
  72. re.match(opts.ignore, "this/is/just/a/test.c")
  73. except:
  74. sys.exit("Please specify a valid Python regex.")
  75. return opts
  76. def main():
  77. """Main function of this module."""
  78. opts = parse_options()
  79. if opts.commit or opts.diff:
  80. head = get_head()
  81. # get commit range
  82. commit_a = None
  83. commit_b = None
  84. if opts.commit:
  85. commit_a = opts.commit + "~"
  86. commit_b = opts.commit
  87. elif opts.diff:
  88. split = opts.diff.split("..")
  89. commit_a = split[0]
  90. commit_b = split[1]
  91. undefined_a = {}
  92. undefined_b = {}
  93. # get undefined items before the commit
  94. execute("git reset --hard %s" % commit_a)
  95. undefined_a = check_symbols(opts.ignore)
  96. # get undefined items for the commit
  97. execute("git reset --hard %s" % commit_b)
  98. undefined_b = check_symbols(opts.ignore)
  99. # report cases that are present for the commit but not before
  100. for feature in sorted(undefined_b):
  101. # feature has not been undefined before
  102. if not feature in undefined_a:
  103. files = sorted(undefined_b.get(feature))
  104. print "%s\t%s" % (feature, ", ".join(files))
  105. # check if there are new files that reference the undefined feature
  106. else:
  107. files = sorted(undefined_b.get(feature) -
  108. undefined_a.get(feature))
  109. if files:
  110. print "%s\t%s" % (feature, ", ".join(files))
  111. # reset to head
  112. execute("git reset --hard %s" % head)
  113. # default to check the entire tree
  114. else:
  115. undefined = check_symbols(opts.ignore)
  116. for feature in sorted(undefined):
  117. files = sorted(undefined.get(feature))
  118. print "%s\t%s" % (feature, ", ".join(files))
  119. def execute(cmd):
  120. """Execute %cmd and return stdout. Exit in case of error."""
  121. pop = Popen(cmd, stdout=PIPE, stderr=STDOUT, shell=True)
  122. (stdout, _) = pop.communicate() # wait until finished
  123. if pop.returncode != 0:
  124. sys.exit(stdout)
  125. return stdout
  126. def tree_is_dirty():
  127. """Return true if the current working tree is dirty (i.e., if any file has
  128. been added, deleted, modified, renamed or copied but not committed)."""
  129. stdout = execute("git status --porcelain")
  130. for line in stdout:
  131. if re.findall(r"[URMADC]{1}", line[:2]):
  132. return True
  133. return False
  134. def get_head():
  135. """Return commit hash of current HEAD."""
  136. stdout = execute("git rev-parse HEAD")
  137. return stdout.strip('\n')
  138. def check_symbols(ignore):
  139. """Find undefined Kconfig symbols and return a dict with the symbol as key
  140. and a list of referencing files as value. Files matching %ignore are not
  141. checked for undefined symbols."""
  142. source_files = []
  143. kconfig_files = []
  144. defined_features = set()
  145. referenced_features = dict() # {feature: [files]}
  146. # use 'git ls-files' to get the worklist
  147. stdout = execute("git ls-files")
  148. if len(stdout) > 0 and stdout[-1] == "\n":
  149. stdout = stdout[:-1]
  150. for gitfile in stdout.rsplit("\n"):
  151. if ".git" in gitfile or "ChangeLog" in gitfile or \
  152. ".log" in gitfile or os.path.isdir(gitfile) or \
  153. gitfile.startswith("tools/"):
  154. continue
  155. if REGEX_FILE_KCONFIG.match(gitfile):
  156. kconfig_files.append(gitfile)
  157. else:
  158. # all non-Kconfig files are checked for consistency
  159. source_files.append(gitfile)
  160. for sfile in source_files:
  161. if ignore and re.match(ignore, sfile):
  162. # do not check files matching %ignore
  163. continue
  164. parse_source_file(sfile, referenced_features)
  165. for kfile in kconfig_files:
  166. if ignore and re.match(ignore, kfile):
  167. # do not collect references for files matching %ignore
  168. parse_kconfig_file(kfile, defined_features, dict())
  169. else:
  170. parse_kconfig_file(kfile, defined_features, referenced_features)
  171. undefined = {} # {feature: [files]}
  172. for feature in sorted(referenced_features):
  173. # filter some false positives
  174. if feature == "FOO" or feature == "BAR" or \
  175. feature == "FOO_BAR" or feature == "XXX":
  176. continue
  177. if feature not in defined_features:
  178. if feature.endswith("_MODULE"):
  179. # avoid false positives for kernel modules
  180. if feature[:-len("_MODULE")] in defined_features:
  181. continue
  182. undefined[feature] = referenced_features.get(feature)
  183. return undefined
  184. def parse_source_file(sfile, referenced_features):
  185. """Parse @sfile for referenced Kconfig features."""
  186. lines = []
  187. with open(sfile, "r") as stream:
  188. lines = stream.readlines()
  189. for line in lines:
  190. if not "CONFIG_" in line:
  191. continue
  192. features = REGEX_SOURCE_FEATURE.findall(line)
  193. for feature in features:
  194. if not REGEX_FILTER_FEATURES.search(feature):
  195. continue
  196. sfiles = referenced_features.get(feature, set())
  197. sfiles.add(sfile)
  198. referenced_features[feature] = sfiles
  199. def get_features_in_line(line):
  200. """Return mentioned Kconfig features in @line."""
  201. return REGEX_FEATURE.findall(line)
  202. def parse_kconfig_file(kfile, defined_features, referenced_features):
  203. """Parse @kfile and update feature definitions and references."""
  204. lines = []
  205. skip = False
  206. with open(kfile, "r") as stream:
  207. lines = stream.readlines()
  208. for i in range(len(lines)):
  209. line = lines[i]
  210. line = line.strip('\n')
  211. line = line.split("#")[0] # ignore comments
  212. if REGEX_KCONFIG_DEF.match(line):
  213. feature_def = REGEX_KCONFIG_DEF.findall(line)
  214. defined_features.add(feature_def[0])
  215. skip = False
  216. elif REGEX_KCONFIG_HELP.match(line):
  217. skip = True
  218. elif skip:
  219. # ignore content of help messages
  220. pass
  221. elif REGEX_KCONFIG_STMT.match(line):
  222. features = get_features_in_line(line)
  223. # multi-line statements
  224. while line.endswith("\\"):
  225. i += 1
  226. line = lines[i]
  227. line = line.strip('\n')
  228. features.extend(get_features_in_line(line))
  229. for feature in set(features):
  230. paths = referenced_features.get(feature, set())
  231. paths.add(kfile)
  232. referenced_features[feature] = paths
  233. if __name__ == "__main__":
  234. main()