checkkconfigsymbols.py 14 KB

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