checkkconfigsymbols.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  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 sorted(undefined_b):
  91. # feature has not been undefined before
  92. if not feature in undefined_a:
  93. files = sorted(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 = sorted(undefined_b.get(feature) -
  98. undefined_a.get(feature))
  99. if files:
  100. print "%s\t%s" % (feature, ", ".join(files))
  101. # reset to head
  102. execute("git reset --hard %s" % head)
  103. # default to check the entire tree
  104. else:
  105. undefined = check_symbols()
  106. for feature in sorted(undefined):
  107. files = sorted(undefined.get(feature))
  108. print "%s\t%s" % (feature, ", ".join(files))
  109. def execute(cmd):
  110. """Execute %cmd and return stdout. Exit in case of error."""
  111. pop = Popen(cmd, stdout=PIPE, stderr=STDOUT, shell=True)
  112. (stdout, _) = pop.communicate() # wait until finished
  113. if pop.returncode != 0:
  114. sys.exit(stdout)
  115. return stdout
  116. def tree_is_dirty():
  117. """Return true if the current working tree is dirty (i.e., if any file has
  118. been added, deleted, modified, renamed or copied but not committed)."""
  119. stdout = execute("git status --porcelain")
  120. for line in stdout:
  121. if re.findall(r"[URMADC]{1}", line[:2]):
  122. return True
  123. return False
  124. def get_head():
  125. """Return commit hash of current HEAD."""
  126. stdout = execute("git rev-parse HEAD")
  127. return stdout.strip('\n')
  128. def check_symbols():
  129. """Find undefined Kconfig symbols and return a dict with the symbol as key
  130. and a list of referencing files as value."""
  131. source_files = []
  132. kconfig_files = []
  133. defined_features = set()
  134. referenced_features = dict() # {feature: [files]}
  135. # use 'git ls-files' to get the worklist
  136. stdout = execute("git ls-files")
  137. if len(stdout) > 0 and stdout[-1] == "\n":
  138. stdout = stdout[:-1]
  139. for gitfile in stdout.rsplit("\n"):
  140. if ".git" in gitfile or "ChangeLog" in gitfile or \
  141. ".log" in gitfile or os.path.isdir(gitfile) or \
  142. gitfile.startswith("tools/"):
  143. continue
  144. if REGEX_FILE_KCONFIG.match(gitfile):
  145. kconfig_files.append(gitfile)
  146. else:
  147. # all non-Kconfig files are checked for consistency
  148. source_files.append(gitfile)
  149. for sfile in source_files:
  150. parse_source_file(sfile, referenced_features)
  151. for kfile in kconfig_files:
  152. parse_kconfig_file(kfile, defined_features, referenced_features)
  153. undefined = {} # {feature: [files]}
  154. for feature in sorted(referenced_features):
  155. # filter some false positives
  156. if feature == "FOO" or feature == "BAR" or \
  157. feature == "FOO_BAR" or feature == "XXX":
  158. continue
  159. if feature not in defined_features:
  160. if feature.endswith("_MODULE"):
  161. # avoid false positives for kernel modules
  162. if feature[:-len("_MODULE")] in defined_features:
  163. continue
  164. undefined[feature] = referenced_features.get(feature)
  165. return undefined
  166. def parse_source_file(sfile, referenced_features):
  167. """Parse @sfile for referenced Kconfig features."""
  168. lines = []
  169. with open(sfile, "r") as stream:
  170. lines = stream.readlines()
  171. for line in lines:
  172. if not "CONFIG_" in line:
  173. continue
  174. features = REGEX_SOURCE_FEATURE.findall(line)
  175. for feature in features:
  176. if not REGEX_FILTER_FEATURES.search(feature):
  177. continue
  178. sfiles = referenced_features.get(feature, set())
  179. sfiles.add(sfile)
  180. referenced_features[feature] = sfiles
  181. def get_features_in_line(line):
  182. """Return mentioned Kconfig features in @line."""
  183. return REGEX_FEATURE.findall(line)
  184. def parse_kconfig_file(kfile, defined_features, referenced_features):
  185. """Parse @kfile and update feature definitions and references."""
  186. lines = []
  187. skip = False
  188. with open(kfile, "r") as stream:
  189. lines = stream.readlines()
  190. for i in range(len(lines)):
  191. line = lines[i]
  192. line = line.strip('\n')
  193. line = line.split("#")[0] # ignore comments
  194. if REGEX_KCONFIG_DEF.match(line):
  195. feature_def = REGEX_KCONFIG_DEF.findall(line)
  196. defined_features.add(feature_def[0])
  197. skip = False
  198. elif REGEX_KCONFIG_HELP.match(line):
  199. skip = True
  200. elif skip:
  201. # ignore content of help messages
  202. pass
  203. elif REGEX_KCONFIG_STMT.match(line):
  204. features = get_features_in_line(line)
  205. # multi-line statements
  206. while line.endswith("\\"):
  207. i += 1
  208. line = lines[i]
  209. line = line.strip('\n')
  210. features.extend(get_features_in_line(line))
  211. for feature in set(features):
  212. paths = referenced_features.get(feature, set())
  213. paths.add(kfile)
  214. referenced_features[feature] = paths
  215. if __name__ == "__main__":
  216. main()