checkkconfigsymbols.py 9.1 KB

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